Mysql SQL选择一个表中的行,另一个表中的键行具有给定值
很难在标题中解释我想要什么,有些我会尝试用一个例子来说明。我有两张桌子:Mysql SQL选择一个表中的行,另一个表中的键行具有给定值,mysql,sql,select,Mysql,Sql,Select,很难在标题中解释我想要什么,有些我会尝试用一个例子来说明。我有两张桌子: [Table1] set_id | data -------+----- 1 | 123 2 | 456 3 | 789 4 | 987 [Table2] set_id | single_id -------+---------- 1 | 10 2 | 10 2 | 13 3 | 10 3 | 13
[Table1]
set_id | data
-------+-----
1 | 123
2 | 456
3 | 789
4 | 987
[Table2]
set_id | single_id
-------+----------
1 | 10
2 | 10
2 | 13
3 | 10
3 | 13
3 | 14
4 | 10
4 | 15
我需要选择Table1
中具有set\u id
的行,而Table2
中具有相同set\u id
的行只有查询中给出的single\u id
s。例如:
对于查询(10,13)
结果行应为2 | 456
对于查询(10)
结果行应为1 | 123
对于查询(10、13、14)
结果行应为3 | 789
如何做到这一点?这是集内集子查询的一个示例。我认为最通用的方法是使用聚合,并使用
having
子句:
select t1.set_id, t1.data
from table1 t1 join
table2 t2
on t1.set_id = t2.set_id
group by t1.set_id
having sum(t2.single_id = 10) > 0 and
sum(t2.single_id = 13) > 0 and
sum(t2.single_id not in (10, 13)) = 0;
having
子句中的每个条件测试一个条件。第一个是存在10
的行;第二行显示的是13
。最后一点是不存在其他值
编辑:
在MySQL中,实际上还有另一种更直观的方法:
select t1.set_id, t1.data
from table1 t1 join
table2 t2
on t1.set_id = t2.set_id
group by t1.set_id
having group_concat(distinct t2.single_id order by t2.single_id) = '10,13';
也就是说,将不同的值按顺序连接在一起,并将它们与常量字符串进行比较。+1)您的答案非常棒。这是您的答案谢谢您的回答!这就是我需要的!