SQL基于两列返回不同的行

时间:2014-05-08 17:49:47

标签: mysql sql

我有以下查询。是的,我知道,我没有发布架构,但所有连接都很好,我认为它不相关。

如何为不同的counties.namecities.states_id返回所有行。

我曾经使用过不同的版本,但从未使用过两列。

谢谢

SELECT c.name AS id, CONCAT(c.name,", ",ci.states_id) AS value
FROM counties AS c
INNER JOIN zipcodes AS z ON z.counties_id=c.id
INNER JOIN cities_has_zipcodes AS chz ON chz.zipcodes_id=z.id
INNER JOIN cities AS ci ON ci.id=chz.cities_id
WHERE c.name LIKE "San Fr"
ORDER BY id LIMIT 100

1 个答案:

答案 0 :(得分:2)

您需要GROUP_CONCAT功能和GROUP BY代替DISTINCT

SELECT c.name AS id, GROUP_CONCAT(c.name, ', ', ci.states_id SEPARATOR ', ') AS value
FROM counties AS c
INNER JOIN zipcodes AS z ON z.counties_id=c.id
INNER JOIN cities_has_zipcodes AS chz ON chz.zipcodes_id=z.id
INNER JOIN cities AS ci ON ci.id=chz.cities_id
WHERE c.name LIKE "San Fr"
GROUP BY c.name, ci.states_id
ORDER BY id LIMIT 100