我會通過保持一致的命名約定在我的表開始,並保持在單數
SELECT article_id = a.article_id
,review_count = COUNT(DISTINCT(r.review_id))
,comment_count = COUNT(DISTINCT(c.comment_id))
FROM article a
LEFT OUTER JOIN review r
ON a.article_id = r.article_id
LEFT OUTER JOIN comment c
ON a.article_id = c.article_id
GROUP BY a.article_id
這裏他們所有命名的一些測試數據一起玩:
-- Create tables
CREATE TABLE article(article_id INT)
CREATE TABLE review(review_id INT, article_id INT)
CREATE TABLE comment(comment_id INT, article_id INT)
-- Create some test data
INSERT INTO article SELECT 1
INSERT INTO article SELECT 2
INSERT INTO article SELECT 3
INSERT INTO review SELECT 10, 1
INSERT INTO review SELECT 20, 2
INSERT INTO review SELECT 30, 2
INSERT INTO review SELECT 40, 3
INSERT INTO review SELECT 50, 3
INSERT INTO review SELECT 60, 3
INSERT INTO comment SELECT 200, 1
INSERT INTO comment SELECT 300, 1
INSERT INTO comment SELECT 400, 2
INSERT INTO comment SELECT 500, 2
INSERT INTO comment SELECT 600, 3
後你大大改變了你的問題,我相信這個查詢會給你一個答案:
SELECT u.content_type_id
,u.object_id
,review_count = SUM(u.review_count)
,comment_count = SUM(u.comment_count)
FROM
(
SELECT content_type_id
,object_id
,review_count = COUNT(*)
,comment_count = 0
FROM review
GROUP BY content_type_id, object_id
UNION
SELECT content_type_id
,object_id
,review_count = 0
,comment_count = COUNT(*)
FROM comment
GROUP BY content_type_id, object_id
) u
GROUP BY u.content_type_id, u.object_id
這裏是一些測試數據一起工作:
CREATE TABLE review(review_id INT, content_type_id INT, object_id INT)
CREATE TABLE comment(comment_id INT, content_type_id INT, object_id INT)
INSERT INTO review SELECT 11, 10, 100
INSERT INTO review SELECT 12, 10, 100
INSERT INTO review SELECT 13, 20, 100
INSERT INTO review SELECT 13, 10, 200
INSERT INTO review SELECT 13, 30, 100
INSERT INTO comment SELECT 21, 10, 100
INSERT INTO comment SELECT 22, 20, 100
INSERT INTO comment SELECT 23, 20, 100
INSERT INTO comment SELECT 24, 20, 100
INSERT INTO comment SELECT 25, 10, 200
INSERT INTO comment SELECT 26, 10, 200
Ramandeep。您已對原始問題進行了重大編輯,將其從3個表更改爲2個表,刪除FK約束並更改要查找的結果集中的列。我相信我的答案正確而完整地回答了你原來的問題。 – 2012-02-09 14:06:20
是的,你已經完全重新定義了這個問題。不酷。此外,你在下面有很多評論,說你想包括'article_id'。 – RedFilter 2012-02-09 15:23:38
是的史蒂芬..你的回答是正確的以前的情況.. !! .. thanx .. !! ..和那些意見是在我修改問題之前添加的..並且對於修改問題感到抱歉..但是我認爲我的場景與我之前描述的類似,所以我會通過答案解決它..再次嘗試..但請你現在可以回答.. !! – 2012-02-09 16:24:10