此查询工作正常,但如果用户在“user_categories”表中没有任何类别,我无法弄清楚为什么它不会返回任何内容?这是表结构:
用户:用户ID,用户名,用户城市
类别:类别ID,类别名称
user_categories:用户ID,类别ID
SELECT users.*, GROUP_CONCAT(categories.category_name) AS categories
FROM users
INNER JOIN user_categories ON users.user_id = user_categories.user_id
INNER JOIN categories ON user_categories.category_id = categories.category_id
WHERE users.user_city = 'brooklyn'
GROUP BY users.user_id
LIMIT 10
如果user_categories中的user_id没有行,我只需要将新列“categories”设为空...
谢谢!
答案 0 :(得分:7)
您使用了错误的连接类型 - 只有在两个表中都找到匹配项时,内连接才会成功。相反,您想尝试外连接。尝试这样的事情:
SELECT users.*, GROUP_CONCAT(categories.category_name) AS categories
FROM users
LEFT OUTER JOIN user_categories ON users.user_id = user_categories.user_id
LEFT OUTER JOIN categories ON user_categories.category_id = categories.category_id
WHERE users.user_city = 'brooklyn'
GROUP BY users.user_id
LIMIT 10
Wikipedia SQL JOIN文章对可用的连接类型进行了相当不错的总结。
答案 1 :(得分:3)
SELECT users.*, GROUP_CONCAT(categories.category_name) AS categories
FROM users
LEFT JOIN
user_categories ON users.user_id = user_categories.user_id
LEFT JOIN
categories ON user_categories.category_id = categories.category_id
WHERE users.user_city = 'brooklyn'
GROUP BY
users.user_id
LIMIT 10
请注意,在MyISAM
表上,子查询解决方案可能更有效:
SELECT users.*,
(
SELECT GROUP_CONCAT(category_name)
FROM user_categories uc
JOIN categories c
ON c.category_id = uc.category_id
WHERE uc.user_id = users.id
) AS categories
FROM users
WHERE users.user_city = 'brooklyn'
ORDER BY
user_id
LIMIT 10
有关详细信息,请参阅我的博客中的这篇文章:
答案 2 :(得分:2)
如果两个表中都没有记录,则内部联接不会返回记录。您可能想要一个左外连接。
答案 3 :(得分:2)
那是因为您对user_categories使用了INNER JOIN
。如果您使用LEFT JOIN
,如果该用户没有相应的ID,则将为该表返回空数据。