entity
---
id name
---
1 one
2 two
3 three
property
---
id name
---
1 prop1
2 prop2
3 prop3
entity_property
---
entity_id property_id
---
1 1
1 2
1 3
2 1
我想獲得至少有1和2(但可以有更多)屬性的實體。選擇哪裏(1和2)在GROUP_CONCAT()
這是一種解決方法,我不喜歡:
SELECT entity_property.entity_id,
(GROUP_CONCAT(entity_property.property_id)) as props
FROM `entity_property`
JOIN entity
ON entity_property.entity_id = entity.id
GROUP BY entity.id
它返回:
entity_id props
---
1 1,2,3
2 1
然後我有服務器的語言爆發,然後排除。
該查詢返回所有實體的行:
SELECT entity.id
FROM entity
WHERE (1 AND 2) IN
(SELECT property_id
FROM entity_property
LEFT JOIN entity
ON entity_property.entity_id = entity.id
WHERE entity_property.entity_id = entity.id)
此查詢導致錯誤:
SELECT entity.id as ent_id
FROM entity
WHERE (1 AND 2) IN
(SELECT property_id
FROM entity_property
LEFT JOIN entity
ON entity_property.entity_id = entity.id
WHERE entity_property.entity_id = ent_id)
見http://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-一個非常簡單的sql查詢 - 但我不回答包含單詞'想'的問題 - 這只是一個規則。 – Strawberry