使用的技术:MySQL 5.1
我在下面有一个MySQL查询:
SELECT
property.propertyId,
categoryRelationships.categoryId
FROM
property
LEFT OUTER JOIN categoryRelationships ON (property.propertyId = categoryRelationships.propertyId)
WHERE
categoryRelationships.categoryId IN (11,12)
返回如下结果:
propertyId categoryId
972 11
1071 11
1622 12
1622 11
但是,我想要做的只是返回propertyId,其中包含类别11和12(在1622以上的情况下)
我试过了
SELECT
property.propertyId,
categoryRelationships.categoryId
FROM
property
LEFT OUTER JOIN categoryRelationships ON (property.propertyId = categoryRelationships.propertyId)
WHERE
categoryRelationships.categoryId = 11
AND categoryRelationships.categoryId = 12
和
SELECT
property.propertyId,
categoryRelationships.categoryId
FROM
property
LEFT OUTER JOIN categoryRelationships ON (property.propertyId = categoryRelationships.propertyId)
WHERE
categoryRelationships.categoryId IN (11)
AND categoryRelationships.categoryId IN (12)
然而,这没有结果,这让我有点疯狂如何做到这一点。
这两个表的一个简单示例是(我从属性表中返回了大量的信息):
categoryRelationships
categoryRelationshipsId categoryId propertyId
2 9 2136
3 2 2136
4 11 1622
5 12 1622
property
propertyId propertyAddress
1622 1 Anystreet
2136 156 Stack Road
答案 0 :(得分:1)
在我看来,这是最明确,最直接的解决方案:
SELECT p.propertyaddress, t1.pid, t1.cid
FROM categoryRelationships t1
LEFT JOIN property p ON p.property_id = t1.property_id
WHERE EXISTS (
SELECT 1
FROM categoryRelationships t2
WHERE t2.pid = t1.pid
AND t2.cid = 11)
AND EXISTS (
SELECT 1
FROM categoryRelationships t3
WHERE t3.pid = t1.pid
AND t3.cid = 12);
由于有时候MySQL不太擅长处理子查询,你可以选择这样做:
SELECT p.propertyaddress, t1.pid, t1.cid
FROM categoryRelationships t1
LEFT JOIN property p ON p.property_id = t1.property_id
JOIN categoryRelationships t2 ON t2.pid = t1.pid
AND t2.cid = 11
JOIN categoryRelationships t3 ON t2.pid = t3.pid
AND t3.cid = 12;