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

表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)


感谢您的建议!

最佳答案

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

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中的列,将会看到过滤。

10-02 14:02