如何从多态数据透视表和2个目标中获得深层关系

时间:2019-02-08 13:01:53

标签: mysql pivot-table

我有一个名为“ taggables”的数据透视表 它包含一个tag_id,一个taggable_id和taggable_type。

taggable_type包含2个值之一(社交帐户或基准)

问题很简单: 基准具有标签,而social_account也具有标签。

我想找到所有具有相同基准的一个或多个基准的帐户

经过一番努力,我想到了这个查询

SELECT *, 
       taggable_id                          AS social_account_id, 
       Group_concat(tag_id ORDER BY tag_id) AS tags 
FROM   `taggables` 
WHERE  taggable_type = "app\\socialaccount" 
GROUP  BY ( social_account_id ) 
HAVING tags IN (SELECT Group_concat(tag_id ORDER BY tag_id) AS tags 
                FROM   `taggables` 
                WHERE  taggable_type = "app\\benchmark" 
                       AND taggable_id IN ( 1, 2 ) 
                GROUP  BY ( taggable_id ))  

上面的查询提供了正确的查询行数,但是在phpMyAdmin中什么都没有显示

如果我向查询添加LIMIT 1,它会返回结果之一。

1 个答案:

答案 0 :(得分:-1)

SELECT *,taggable_id as social_account_id, GROUP_CONCAT(tag_id ORdeR by tag_id) as tags FROM `taggables` 
WHERE taggable_type LIKE '%SocialAccount%'
GROUP BY (social_account_id) 
HAVING tags IN ( 
    SELECT GROUP_CONCAT(tag_id ORdeR by tag_id) as tags FROM `taggables` 
    WHERE taggable_type LIKE '%Benchmark%' AND taggable_id IN (1,2) 
    GROUP BY (taggable_id)
 )