我想计算两个表中相同用户ID的出现次数。
jos_findme
表中包含所有用户。另外两个也有“用户ID”列。
但我想要两张桌子的整体数量。我试过这个,但它不起作用?
SELECT
c.user_id, count(c.user_id) AS counter
FROM
jos_findme as c
LEFT JOIN
jos_findme_bestof as b ON b.user_id = c.user_id
LEFT JOIN
jos_findme_pair as p ON p.user_id = c.user_id
WHERE
c.user_id > 0
GROUP BY c.user_id
ORDER BY counter DESC
LIMIT 10
所有表都有“user_id”列。我只想在表“jos_findme_bestof”和“jos_findme_pair”中计算它们
答案 0 :(得分:2)
相关的子查询在这里很有用:
SELECT c.user_id,
(SELECT Count(*)
FROM jos_findme_bestof b
WHERE b.user_id = c.user_id),
(SELECT Count(*)
FROM jos_findme_pair p
WHERE p.user_id = c.user_id)
FROM jos_findme c
答案 1 :(得分:0)
我认为你可以这样做:
SELECT AA.user_id, AA.Acounter + BB.Bcounter
from (SELECT a.user_id, count(a.user_id) AS Acounter
FROM jos_findme_bestof as a
GROUP BY a.user_id) as AA
Join
(SELECT b.user_id, count(b.user_id) AS Bcounter
FROM jos_findme_pair as b
GROUP BY b.user_id) as BB
on AA.user_id = BB.user_id
如果你想要所有的id(意思是jos_findme_pair中的id不在jos_findme_bestof中) - 使用FULL OUTER JOIN
答案 2 :(得分:0)
试试这个
SELECT c.user_id,
Users1 = (SELECT COUNT(*) FROM jos_findme_bestof b WHERE b.user_id = c.user_id),
Users2 = (SELECT COUNT(*) FROM jos_findme_pair p WHERE p.user_id = c.user_id),
TotalUser = (SELECT COUNT(*) FROM jos_findme_bestof b WHERE b.user_id = c.user_id)
+
(SELECT COUNT(*) FROM jos_findme_pair p WHERE p.user_id= c.user_id)
FROM
jos_findme c
下面,
Users1将返回jos_findme_bestof
的所有用户
Users2将返回jos_findme_pair
的所有用户
TotalUser将计算两个表
希望它会对你有所帮助! 感谢。
答案 3 :(得分:0)
试试这个:
SELECT c.user_id, (IFNULL(b.bCount, 0) + IFNULL(p.pCount, 0)) AS counter
FROM jos_findme AS c
LEFT JOIN (SELECT b.user_id, COUNT(1) bCount
FROM jos_findme_bestof b
GROUP BY b.user_id
) AS b ON b.user_id = c.user_id
LEFT JOIN (SELECT p.user_id, COUNT(1) pCount
FROM jos_findme_pair p
GROUP BY p.user_id
) AS p ON p.user_id = c.user_id
WHERE c.user_id > 0
GROUP BY c.user_id
ORDER BY counter DESC
LIMIT 10