MySQL:连接一个包含多行条件的表

时间:2018-12-17 14:20:25

标签: mysql sql join

尝试从联接表中选择一些行,其中有多个相关行。
这是原始查询的非常简化的版本,因此请不要对常规表结构提出任何建议。

表A

id, title
------------
1, housea
2, houseb
3, housec
4, housed

表B

id, cid, attrib, val
--------------------
1, 1, bathrooms, 2
2, 1, bedrooms, 1
3, 2, bathrooms, 0
4, 1, pools, 1
5, 2, bedrooms, 1
6, 2, pools, 1
7, 3, bathrooms, 1
8, 4, bathrooms, 1
9, 4, bedrooms, 1

选择所有至少具有一间浴室和一间卧室的对象。

因此,只有这两个应出现:

2, housea
4, housed

这不起作用:

SELECT a.id, title
FROM tablea a
LEFT JOIN tableb b ON b.cid = a.id
WHERE (b.attrib = "bathrooms" AND b.val > 0) AND (b.attrib = "bedrooms" AND b.val > 0)

也不是:

SELECT a.id, title
FROM tablea a
LEFT JOIN tableb b1 ON b1.cid = a.id AND (b1.attrib = "bathrooms" AND b1.val > 0) 
LEFT JOIN tableb b2 ON b2.cid = a.id AND (b2.attrib = "bedrooms" AND b2.val > 0) 

感谢您的建议!

2 个答案:

答案 0 :(得分:1)

您的第二个版本基本上是正确的,除了您需要内部联接:

SELECT a.id, a.title
FROM tablea a JOIN
     tableb b1
     ON b1.cid = a.id AND (b1.attrib = 'bathrooms' AND b1.val > 0) JOIN
     tableb b2
     ON b2.cid = a.id AND (b2.attrib = 'bedrooms' AND b2.val > 0) ;

您所有的过滤都在ON子句中,因此实际上没有任何行被过滤掉。如果查看b1b2中的列,则会看到过滤条件。

答案 1 :(得分:0)

尝试如下运行Correlated子查询:

select a.id, a.title from tablea a where 2 >= 
(select count(b.cid) from tableb b where b.cid = a.id and b.attrib in ('bathrooms' , 'bedrooms') and b.val > 0 group by b.cid)