我正在尝试使用SUM
函数来计算来自3个表的行,但是,由于返回total_files
和total_notes
时它们都不能正常工作,它们都是如果至少有一个文件,那么total_files
将采用与total_notes
相同的值,我不明白为什么会这样做。
它应该计算与每条记录相关的行数,这些记录将作为记录列表返回,其中包含每个记录行分配给记录的总文件数,总记录数和总联系数(文件数据,备注)和联系人不会只显示计数)。
我的查询如下所示:
SELECT rec.street_number,
rec.street_name,
rec.city,
rec.state,
rec.country,
rec.latitude,
rec.longitude,
LEFT(rec.description, 250) AS description,
usr.username,
usr.full_name,
ppl.person_id,
ppl.first_name,
ppl.last_name,
SUM(IF(rlk.record_id = rec.record_id, 1, 0)) AS total_contacts,
SUM(IF(files.record_id = rec.record_id, 1, 0)) AS total_files,
SUM(IF(notes.record_id = rec.record_id, 1, 0)) AS total_notes,
(
SELECT COUNT(DISTINCT rec.record_id)
FROM records rec
WHERE rec.marked_delete = 0 AND rec.is_archive = 0
) AS total_records
FROM
(
records rec
INNER JOIN members usr ON rec.user_id = usr.user_id
LEFT OUTER JOIN record_links rlk ON rec.record_id = rlk.record_id
LEFT OUTER JOIN people ppl ON ppl.person_id = rlk.person_id AND rlk.record_id = rec.record_id
LEFT OUTER JOIN files files ON files.record_id = rec.record_id
LEFT OUTER JOIN notes notes ON notes.record_id = rec.record_id
)
WHERE rec.marked_delete = 0 AND rec.is_archive = 0
GROUP BY rec.record_id
ORDER BY rec.submit_date DESC
LIMIT 0, 25
基本上,您可以看到三 SUM
会计算来自这些表的相关行,但我真的不明白total_files
将如何处理与total_notes
相同的价值我在这里做错了吗?
答案 0 :(得分:1)
因为rec
已加入 notes
和files
。
假设记录1有2个音符和1个文件,记录2有两个音符和两个文件,而记录3有一个音符但没有文件。
然后表格rec LEFT OUTER JOIN files ... LEFT OUTER JOIN notes
将如下所示:
+-----------+---------+---------+
| record_id | file_id | note_id |
+-----------+---------+---------+
| 1 | 1 | 1 |
| 1 | 2 | 1 |
| 2 | 3 | 2 |
| 2 | 3 | 3 |
| 2 | 4 | 2 |
| 2 | 4 | 3 |
| 3 | NULL | 4 |
+-----------+---------+---------+
请注意每个file_id
如何加入每个note_id
(在同一record_id
内)。此外,由于您SUM(IF(files.record_id = rec.record_id,1,0))
和的加入条件为files.record_id = rec.record_id
,因此您实际上每COUNT(files)*COUNT(notes)
计算record_id
。
我建议您改为COUNT(DISTINCT files.id)
和COUNT(DISTINCT records.id)
。 COUNT
中的列将是files
/ notes
上的主键,不 files.record_id
:
SELECT rec.record_id,
COUNT(DISTINCT files.id) AS total_files,
COUNT(DISTINCT notes.id) AS total_notes
FROM rec
-- note: LEFT OUTER JOIN is the same as LEFT JOIN in MySQL
LEFT JOIN files ON files.record_id=rec.record_id
LEFT JOIN notes ON notes.record_id=rec.record_id
GROUP BY record_id
+-----------+-------------+-------------+
| record_id | total_files | total_notes |
+-----------+-------------+-------------+
| 1 | 2 | 1 |
| 2 | 2 | 2 |
| 3 | 0 | 1 |
+-----------+-------------+-------------+
当然,根据需要调整您的查询(添加那些额外的列/连接)。