在GROUP_CONCAT()

时间:2017-01-09 12:07:10

标签: mysql group-concat

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(但可能拥有更多)属性的实体。

这是我不喜欢的解决方法:

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)

3 个答案:

答案 0 :(得分:0)

您可以使用group byhaving

获取实体ID
SELECT ep.entity_id
FROM `entity_property` ep
WHERE ep.property_id IN (1, 2)
GROUP BY ep.entity_id
HAVING COUNT(DISTINCT ep.property_id) = 2;

注意:

  • 这不需要entity表。
  • 如果DISTINCT中不允许重复对,则无需entity_property
  • 要获得更多属性,您需要更改WHEREHAVING(其中" 2"是您想要匹配的内容的数量)。

答案 1 :(得分:0)

您感兴趣的是entity中记录entity_property且值为1或2的所有记录。为此,您可以使用限制因素进行内部联接entity_property ,例如

SELECT
    e.*
FROM entity e
INNER JOIN entity_property ep1
    ON ep1.entity_id = e.id
    AND ep1.property_id = 1
INNER JOIN entity_property ep2
    ON ep2.entity_id = e.id
    AND ep2.property_id = 2

内部联接确保仅返回entityentity_property中相应行的记录。双连接允许您确保entity行同时具有1和2.使用简单连接允许使用索引,例如entity_property ( property_id , entity_id )上的索引

答案 2 :(得分:0)

您可以使用conditional having子句找到具有至少1,2的property_ids的entity_id,并获取group_concat。

试试这个:

CTRL+Z