2

我有三张桌子

  • resources_connection
    1. resource_id
    2. resource_tag_id
  • resources_flags
    1. 用户身份
    2. resource_id
  • resources_votes
    1. 用户身份
    2. resource_id

每个都是一个 2 列的表,int (11) 旨在让我根据单个“资源 ID”查询标签、标志和投票的数量

我目前正在使用此查询来尝试获取标签(resources_connection)、标志(resources_flags)和投票(resources_votes)的计数:

SELECT COUNT(DISTINCT t1.resource_id) as votes,
        COUNT(DISTINCT t2.resource_id) as flags,
        COUNT(DISTINCT t3.resource_tag_id) as tags
FROM ecruit_demo.resources_votes t1
LEFT JOIN ecruit_demo.resources_flags t2
    ON (t1.resource_id = t2.resource_id)
JOIN ecruit_demo.resources_connection t3
    ON (t1.resource_id = t3.resource_id) WHERE t1.resource_id = 4

问题是这个查询返回了正确的结果,resource_id = 1但是当我设置resource_id4(有一个标签)时,它返回全零。什么是正确的查询结构来确保这个查询总是返回给定的标签、标志和投票的正确计数resource_id

我还应该补充一点,数据库中唯一出现resource_id = 4的地方是在resources_connection中,其他两个表没有这个值

4

2 回答 2

3
SELECT  resource_ID,
        MAX(CASE WHEN types = 'votes' THEN totals ELSE NULL END) votes,
        MAX(CASE WHEN types = 'flags' THEN totals ELSE NULL END) flags,
        MAX(CASE WHEN types = 'tags' THEN totals ELSE NULL END) tags
FROM    
    (
        SELECT  resource_ID, 'votes' types, 
                COUNT(DISTINCT resource_ID) totals
        FROM    resources_votes
        GROUP   BY resource_ID
        UNION
        SELECT  resource_ID, 'flags' types, 
                COUNT(DISTINCT resource_ID) totals
        FROM    resources_flags
        GROUP   BY resource_ID
        UNION
        SELECT  resource_ID, 'tags' types, 
                COUNT(DISTINCT resource_tag_id) totals
        FROM    resources_connection
        GROUP   BY resource_ID
    ) s
-- WHERE    resource_ID = 1
GROUP   BY resource_ID
于 2013-02-08T02:39:43.377 回答
0

我在 mysql 方面不是很好,但也许你可以试试:

将 JOIN 更改为 LEFT JOIN,这样查询将是这样的。

 SELECT COUNT(DISTINCT t1.resource_id) as votes,
            COUNT(DISTINCT t2.resource_id) as flags,
            COUNT(DISTINCT t3.resource_tag_id) as tags
    FROM ecruit_demo.resources_votes t1
    LEFT JOIN ecruit_demo.resources_flags t2
        ON (t1.resource_id = t2.resource_id)
    LEFT JOIN ecruit_demo.resources_connection t3
        ON (t1.resource_id = t3.resource_id) WHERE t1.resource_id = 4
于 2013-02-08T02:41:43.980 回答