我在 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 |
+-----+----------+--------+------+---------+
有一个问题叫做: 创建一个查询来显示学生表,其中包含年龄超过 18 岁且具有唯一性的学生 城市。
根据我的说法,所需的输出:
+-----+----------+--------+------+---------+
| 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 |
+-----+----------+--------+------+---------+
我尝试过以下方法:
mysql> select distinct place from student where age>18;
+---------+
| place |
+---------+
| chennai |
| delhi |
+---------+
2 rows in set (0.05 sec)
我尝试向放置字段添加唯一键以使用 cbe
删除第二条记录,但我的假设是错误的。
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 |
+-------+
另外,
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)
当我在不同的地方使用多个字段时,它的独特特征就丢失了!!!
我应该对上述任何查询进行哪些更改才能获得所需的输出???
提前致谢。
最佳答案
Create a query to display the student table with students of age more than 18 with unique city
我对此的理解是:学生应该超过 18 岁,并且他们的位置
应该只在表格中出现一次。只有一行符合此条件,即 ano 118
(Aathmika 19 岁,没有其他学生住在德里)。
您可以将其表述为:
select s.*
from student s
where
age > 18
and not exists(select 1 from student s1 where s1.place = s.place and s1.ano <> s.ano)
关于mysql - 查询显示年龄超过 18 岁且具有唯一城市的学生的学生表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64495742/