My table in MySQL :
mysql> select * from student;
+-----+----------+--------+------+---------+
| ano | name | gender | age | place |
+-----+----------+--------+------+---------+
| 114 | ron | m | 18 | cbe |
| 115 | dhruv | m | 18 | cbe |
| 116 | mini | f | 23 | chennai |
| 117 | yash | m | 20 | chennai |
| 118 | aathmika | f | 19 | delhi |
| 119 | aadhi | m | 9 | pune |
+-----+----------+--------+------+---------+
There was a question called : Create a query to display the student table with students of age more than 18 with unique city.
According to me, required output :
+-----+----------+--------+------+---------+
| ano | name | gender | age | place |
+-----+----------+--------+------+---------+
| 116 | mini | f | 23 | chennai |
| 118 | aathmika | f | 19 | delhi |
+-----+----------+--------+------+---------+
Or
+-----+----------+--------+------+---------+
| ano | name | gender | age | place |
+-----+----------+--------+------+---------+
| 117 | yash | m | 20 | chennai |
| 118 | aathmika | f | 19 | delhi |
+-----+----------+--------+------+---------+
I've tried the following :
mysql> select distinct place from student where age>18;
+---------+
| place |
+---------+
| chennai |
| delhi |
+---------+
2 rows in set (0.05 sec)
I tried to add unique key to place field to delete the second record with cbe
, whereas my assumption was wrong.
mysql> alter table student add constraint unique(place);
ERROR 1062 (23000): Duplicate entry 'cbe' for key 'place'
mysql> alter table student modify place char(10) unique;
ERROR 1062 (23000): Duplicate entry 'cbe' for key 'place'
mysql> alter table student change place place char(10) unique;
ERROR 1062 (23000): Duplicate entry 'cbe' for key 'place'
mysql> select place from student where age>18 group by place having count(place)
=1;
+-------+
| place |
+-------+
| delhi |
+-------+
Also,
mysql> select distinct place,name,ano,age from student where age>18;
+---------+----------+-----+------+
| place | name | ano | age |
+---------+----------+-----+------+
| chennai | mini | 116 | 23 |
| chennai | yash | 117 | 20 |
| delhi | aathmika | 118 | 19 |
+---------+----------+-----+------+
3 rows in set (0.00 sec)
When I use many fields along with distinct place, it's distinct characteristic is lost!!!
What changes shall I make in any of the above queries to get the desired output???
Thanks in advance.