我有一张成员表和一份清单表。我想获取一个成员列表并获取他们发布的列表数量。出于某种原因,我当前的查询在应该是6时返回值为30.我现在完全误解了连接或计数功能吗?
这是我的查询。是的,m.user_id应该是那个,而不是像列表中显示的m.member_id。
SELECT m.user_id AS id, m.group_id, m.email_address, m.display_name, m.status,
UNIX_TIMESTAMP(m.join_date) AS join_date, m.about, m.facebook_url,
m.twitter_url, m.address, m.region_id, m.city, m.zip, m.avatar_id,
g.group_id, g.title AS group_title, p.group_id, p.context,
GROUP_CONCAT(p.context) AS permissions,
r.region_id, r.title AS region_title,
a.attachment_id, a.file_path AS avatar_path,
l.member_id, COUNT(l.member_id) AS total_listings
FROM users AS m
LEFT JOIN groups AS g ON m.group_id = g.group_id
LEFT JOIN permissions AS p ON m.group_id = p.group_id
LEFT JOIN regions AS r ON m.region_id = r.region_id
LEFT JOIN attachments AS a ON m.avatar_id = a.attachment_id
LEFT JOIN listings AS l ON m.user_id = l.member_id
WHERE m.user_id = 1
GROUP BY m.user_id
LIMIT 1
答案 0 :(得分:0)
您想在分组后计算。您正在计算由于连接而包含重复项的总行数。尝试像
这样的东西SELECT x.*, COUNT(total_listings) as count FROM (
SELECT m.user_id AS id, m.group_id, m.email_address, m.display_name, m.status, UNIX_TIMESTAMP(m.join_date) AS join_date, m.about, m.facebook_url, m.twitter_url, m.address, m.region_id, m.city, m.zip, m.avatar_id,
g.group_id, g.title AS group_title, p.group_id, p.context, GROUP_CONCAT(p.context) AS permissions,
r.region_id, r.title AS region_title,
a.attachment_id, a.file_path AS avatar_path,
l.member_id, l.member_id AS total_listings
FROM users AS m
LEFT JOIN groups AS g ON m.group_id = g.group_id
LEFT JOIN permissions AS p ON m.group_id = p.group_id
LEFT JOIN regions AS r ON m.region_id = r.region_id
LEFT JOIN attachments AS a ON m.avatar_id = a.attachment_id
LEFT JOIN listings AS l ON m.user_id = l.member_id
WHERE m.user_id = 1
GROUP BY m.user_id) x