SQL选择一个表中的行,其中另一个表中的键行已赋值

时间:2014-03-16 13:13:33

标签: mysql sql select

很难在标题中解释我想要的内容,有些我会尝试用这里的例子来做。我有2张桌子:

[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_id行,Table2set_id只有single_id (10, 13)只有查询中给出的行2 | 456。例如:

对于查询(10),结果行应为1 | 123

对于查询(10, 13, 14),结果行应为3 | 789

对于查询{{1}},结果行应为{{1}}。

如何做到这一点?

1 个答案:

答案 0 :(得分:2)

这是set-within-sets子查询的示例。我认为最常用的方法是使用带有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';

也就是说,按顺序将不同的值连接在一起,并将它们与常量字符串进行比较。