我的数据库中有 3 个表。
- ab_contacts
- id
- first_name
- last_name
- addressbook_id
- etc (more, but these are the relevant ones)
- ab_addressbooks
- name
- id
- co_comments
- id
- link_id
- comment
我想创建一个查询,让我选择给定地址簿中的所有联系人和与其相关的评论。
要选择给定地址簿中的所有人员,我可以使用:
从 ab_contacts 中选择 count(*),其中 addressbook_id = '50';
这会返回 8152 人。
但是,当我运行查询时:
select
ab_addressbooks.name,
ab_contacts.first_name,
ab_contacts.last_name,
ab_contacts.email,
ab_contacts.email2,
ab_contacts.email3,
ab_contacts.function,
ab_contacts.address,
ab_contacts.address_no,
ab_contacts.city,
ab_contacts.state,
ab_contacts.zip,
ab_contacts.home_phone,
ab_contacts.work_phone,
ab_contacts.cellular,
REPLACE(REPLACE(REPLACE(ab_contacts.comment, '\r', ', '), '\n', ', '), '\\', '') AS comment,
REPLACE(REPLACE(REPLACE(group_concat(co_comments.comments separator ', '), '\r', ', '), '\n', ', '), '\\', '') AS comment2
from ab_contacts
LEFT JOIN ab_addressbooks ON (ab_contacts.addressbook_id = ab_addressbooks.id)
LEFT JOIN co_comments ON (ab_contacts.id = co_comments.link_id)
WHERE ab_contacts.addressbook_id = '344';`
该格式有效,但我只得到 1045 个结果。我确信我缺少一些东西,但我无法弄清楚。任何帮助将不胜感激。
最佳答案
尝试将您的JOIN
替换为LEFT JOIN
,以吸引没有评论的人,如果可以的话,也许还可以添加一个GROUP BY ab_contacts.id
结果很多行
关于mysql 查询从 3 个表连接信息 - 得到不正确的结果计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11435771/