MySQL查询从5个表中选择连接

时间:2012-10-01 07:58:44

标签: mysql database join left-join

我有5张桌子:

tag: {tagID,tagDetails}
user: {userID,userDetails,u_status=[active or banned]}
subscribe: {tagID,userID}
item: {itemID, itemDetails,i_status=[active or banned]}
item_tag: {tagID,itemID}

我想选择这些数据:

result: {tagID, tagDetails, num_subscribers, num_items}

对于每个tagID,num_subscribers是表用户下的用户数,其u_status为'active'且其userID和所述tagID存在于表subscribe中

对于每个tagID,num_items是表项下的用户数,其i_status为“活动”且其itemID和表tag_中存在的itemID和标签

另外,我希望所有tagID都出现在结果中。如果没有用户订阅或与该tagID相关联的项目,则记录将为

{tagID,tagDetails,0,0}

产生此结果的一个嵌套查询的最佳(尽可能“人类可读”)是什么?

1 个答案:

答案 0 :(得分:1)

这就是你要追求的吗?

        SELECT T.tagID, T.tagDetails, count(distinct U.u_status), count(distinct I.i_status)
        FROM tag T
             JOIN subscribe S ON T.tagID = S.tagID
             JOIN user U ON S.userID = U.userID
             JOIN item_tag IT ON T.tagID = IT.tagID
             JOIN item I ON IT.itemID = I.itemID
        WHERE U.u_status = 'active' and I.i_status = 'active'
        GROUP BY T.tagID

        UNION

        (SELECT tagID, tagDetails, 0, 0
        FROM tag
        EXCEPT
        SELECT T.tagID, T.tagDetails, 0, 0
        FROM tag T
             JOIN subscribe S ON T.tagID = S.tagID
             JOIN user U ON S.userID = U.userID
             JOIN item_tag IT ON T.tagID = IT.tagID
             JOIN item I ON IT.itemID = I.itemID
        WHERE U.u_status = 'active' and I.i_status = 'active'
        GROUP BY T.tagID)

你可能不得不摆弄括号和别名。