[英]Counting rows from 2 MySQL tables JOIN with 3th and ORDER BY highest counting result
我正在嘗試從2個表中計數帖子,並加入保留名稱的第三個表,但是我確實遇到了麻煩。
T1 - id, message, id_users
T2 - id, reply, id_users
T3 - id, name
T1只有主題,T2只有主題的答復,T3只有名稱的用戶信息。
我想要統計,哪個用戶擁有最多的帖子(包括主題),像這樣:
user1 - 454 total (topics + posts)
user2 - 421 total (topics + posts)
等等..
我真的不能用SQL來做到這一點,我所知道的一切都將無法工作,也無法弄清楚,我可能寫給ORDER BY的內容將使ORDER從最高職位到最低職位。
你可以做一個UNION
的T1
和T2
,然后加入與resutlt T3
,最后做一個GROUP BY
到COUNT
的職位數,像這樣:
SELECT names, COUNT(*) as posts
FROM T3
JOIN (
SELECT id_users FROM T1
UNION All
SELECT id_users FROM T2
) as t
ON T3.id = t.id_users
GROUP BY id_users
select t3.name, count(*) from
t3 inner join
(select id_users from t1
union all
select id_users from t2) as posts
on posts.id_users=t3.id
group by 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.