mysql 查询从 3 个表连接信息 - 得到不正确的结果计数

标签 mysql join

我的数据库中有 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/

相关文章:

sql-server - 查询性能 - INNER Join 过滤

c# - Linq 将结果连接到列表

php - php中的mysql查询循环

mysql - 左外连接子查询

mysql - 帮忙在 Codeigniter 中加入 MySQL(标签)表?

mysql - 通过内部连接或左/右连接替换与标量子查询的比较

mysql - 根据结果​​插入一条自动递增的记录

mysql - 仅当两行(不是任一行)都满足时才选择条件

php - 使用 php 和 mysql 检索当月、当周、当日的行

MYSQL - 连接 2 个表,左表上有完整的行