[英]MySQL query to select join from 5 tables
I have 5 tables: 我有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}
I want to select these data: 我想选择这些数据:
result: {tagID, tagDetails, num_subscribers, num_items}
For each tagID, num_subscribers is the number of users under the table user whose u_status is 'active' and whose userID and the said tagID exists in the table subscribe 对于每个标记ID,num_subscribers是表用户下其u_status为“活动”并且其用户ID和所述标记ID存在于表subscribe中的用户数。
For each tagID, num_items is the number of users under the table item whose i_status is 'active' and whose itemID and the said tagID exists in the table item_tag 对于每个tagID,num_items是表项下其i_status为“活动”且其itemID和所述tagID存在于表item_tag中的用户数
Also, I want all the tagID to appears in the result. 另外,我希望所有的tagID都出现在结果中。 If there are no users subscribing or items associated with that tagID, the record will be
如果没有用户订阅或与该tagID相关联的项目,则记录为
{tagID,tagDetails,0,0}
What is the best (as 'human readable' as possible) one nested query that produce this result? 产生此结果的最佳嵌套查询(最好是“人类可读”)是什么?
Is this what you're after? 这是你所追求的吗?
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)
You might have to fiddle with the brackets and aliasing. 您可能不得不摆弄括号和别名。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.