[英]MySQL SELECT COUNT from one table and ID from another?
我正在嘗試從兩個不同的表中查詢信息,但是我沒有弄清楚如何做到最好。 作為免責聲明,我仍在學習MySQL / PHP,並且在設置表時無法控制它們-我正在嘗試使用已有的表,因為我無法添加/更改表。 下表是表格和相關屬性:
Table(attribute1, attribute2, ...);
------------------------------------
reports(id, reporter_id, added)
report_comments(comment_id, report_id, comment_text, commenter_id)
report_id是提交報告的用戶,commenter_id與reporter_id 不是同一個人。
我想對每個reporter_id計數多少個評論注釋,例如,comment_text中的單詞“ incorrect”。 然后,我想制作一個表格,顯示每個記者的ID和自“ 1383359439”(時間戳)以來與該記者的報告相關聯的評論數。
到目前為止,我還不太成功。 我當前的查詢如下所示:
SELECT r.id, r.reporter_id,
(SELECT COUNT(*) FROM report_comments WHERE comment_text LIKE '%incorrect%' AND report_id = r.id) AS comments
FROM reports AS r
LEFT JOIN report_comments AS rc ON r.id = rc.report_id
WHERE r.added > 1383359439
GROUP BY r.reporter_id;
當我將HTML表格設置為列出“ reporter_id”后跟“評論”時,結果頁面為自列出時間以來提交過報告的每個人提供計數,但計數為“ 0”或“ 1”,而任何報告者在任何報告注釋中“不正確”得到“ 1”,而沒有“不正確”的那些得到“ 0”:
Reporter1 | 0
Reporter2 | 1
Reporter3 | 0
Reporter4 | 1
Reporter5 | 1
問題是,有些記者的評論中有幾條帶有“不正確”的注釋,我想對每一個進行計數,僅針對那些記者(不是從未有過“錯誤”注釋的那些記者)。 例如:
Reporter2 | 2
Reporter4 | 17
Reporter5 | 3
我顯然缺少某些東西-我在做什么錯?
您需要為此使用分組。
SELECT
r.reporter_id AS `reporter_id`,
COUNT(rc.report_id) AS `incorrect_count`
FROM reports AS r
INNER JOIN report_comments AS rc
ON r.id = rc.report_id
WHERE rc.comment_text LIKE '%incorrect%'
AND r.added > ?
GROUP BY `reporter_id`
在這里?
表示您要比較的時間戳。
要回答您的后續問題,有兩種方法可以解決此問題。 我可能建議將SUM()
與CASE
結合使用,如下所示:
SELECT
r.reporter_id AS `reporter_id`,
SUM(
CASE WHEN rc.comment_text LIKE '%incorrect%'
THEN 1
ELSE 0
END CASE
) AS `incorrect_count`,
SUM(
CASE WHEN rc.comment_text LIKE '%fake%'
THEN 2
ELSE 0
END CASE
) AS `fake_count`,
FROM reports AS r
INNER JOIN report_comments AS rc
ON r.id = rc.report_id
WHERE
rc.comment_text LIKE '%incorrect%'
OR rc.comment_text LIKE '%fake%'
AND r.added > ?
GROUP BY `reporter_id`
你可以試試
SELECT r.id, COUNT(c.id) tot
FROM reports r INNER JOIN report_comments
ON r.id = c.report_id
AND c.comment_text LIKE '%incorrect%'
AND r.added > 1383359439
GROUP BY r.reporter_id
就像這樣:
SELECT r.reporter_id, COUNT(*) comments
FROM reports AS r
INNER JOIN report_comments AS rc ON r.id = rc.report_id
WHERE r.added > 1383359439
AND comment_text LIKE '%incorrect%'
GROUP BY r.reporter_id;
我刪除了r.id,因為在這種情況下沒有任何意義,因為一個報告者可以擁有許多報告(因此有多個r.id)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.