繁体   English   中英

MySQL SELECT COUNT从一个表和ID从另一个表?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM