我有三张桌子
1)review_trans
2)user_comment_trans
第3)helpful_review_trans
表结构如下所示
review_id(pk) | review_desc | user_id
--------------+----------------+-----------
1 | hello world | 1
2 | test2 | 1
3 | test3 | 2
comment_id | review_id | user_id
------------+--------------+------------
1 | 1 | 4
2 | 1 | 2
3 | 2 | 3
helpful_review_id | review_id | user_id
------------------+------------+------------
1 | 1 | 4
2 | 1 | 2
3 | 2 | 3
我希望每次审核都能获得有用的投票和评论。 所以我想要的输出是这样的
review_id review_desc count(helpful_review_id) count(comment_id)
------------+------------------+----------------------------+--------------------
1 | hello world | 2 | 2
2 | test2 | 1 | 1
3 | test3 | |
我无法获得此记录。我尝试加入表格,但它只显示了一个review_desc 请指教和帮助。
答案 0 :(得分:0)
使用左连接计数(不同)
select r.review_id,
r.review_desc,
count(distinct u.comment_id),
count(distinct h.helpful_review_id)
from review_trans r
left join user_comment_trans u on(r.review_id = u.review_id)
left join helpful_review_trans h on(r.review_id = h.review_id)
group by r.review_id
答案 1 :(得分:0)
SELECT rt.review_id, rt.review_desc,
COUNT(DISTINCT hrt.helpful_review_id), COUNT(DISTINCT uct.comment_id)
FROM review_trans rt
LEFT JOIN helpful_review_trans hrt ON rt.review_id = hrt.review_id
LEFT JOIN user_comment_trans uct ON uct.review_id = rt.review_id
GROUP BY rt.review_id
答案 2 :(得分:0)
SELECT rt.review_id, rt.review_desc, helpful_count, comment_count
FROM review_trans AS rt
LEFT JOIN (
SELECT review_id, COUNT(*) AS comment_count
FROM user_comment_trans
GROUP BY review_id) AS uct ON rt.review_id = uct.review_id
LEFT JOIN (
SELECT review_id, COUNT(*) AS helpful_count
FROM helpful_review_trans
GROUP BY review_id) AS hrt ON rt.review_id = hrt.review_id
答案 3 :(得分:0)
你可以这样做:
SELECT
review_trans.review_id,
review_trans.review_desc,
(
SELECT
COUNT(*)
FROM
helpful_review_trans
WHERE
helpful_review_trans.review_id=review_trans.review_id
) AS helpful_review_id,
(
SELECT
COUNT(*)
FROM
user_comment_trans
WHERE
user_comment_trans.review_id=review_trans.review_id
) AS CountComment_id
FROM
review_trans