我有以下MySQL查询加入另外两个表..
SELECT plants.plant_id,
plants.scientific_name,
plants_features.features,
plants_features.features_id
FROM plants_features,
plants2features,
plants
WHERE plants_features.features_id = plants2features.features_id
AND plants2features.plant_id = plants.plant_id
我很满意输出。
plant_id,scientific_name,features,features_id
3,"Actaea matsumurae 'White Pearl' (Bugbane)","colourful fruit",6
11,"Heuchera 'Beauty Colour' (Coral bells)","salt resistant/coastal",15
18,"Phyllostachys nigra (Black bamboo)","colourful bark",5
26,"Carex morrowii 'Silver Sceptre' (Japanese sedge)","drought tolerant",18
27,"Heuchera 'Obsidian' (Coral bells)","salt resistant/coastal",15
29,"Dianella tasmanica 'Tas Red' (Flax lily)","drought tolerant",18
38,"Stipa tenuissima (Mexican feather grass)","attractive seed-heads",2
38,"Stipa tenuissima (Mexican feather grass)","invasive/self seed/suckering",13
您可以从plant_id' 38' (底部两行)它每条记录输出多行。
我的问题是伙计们,你能否告诉你新的MySQL查询究竟需要什么来确保一行记录中的多行是' plant_id'?
提前致谢, 理查德。
答案 0 :(得分:3)
您需要分组和aggregation functions
。您可以使用GROUP_CONCAT
获取以逗号分隔的列表:
SELECT plants.plant_id,
plants.scientific_name,
GROUP_CONCAT(plants_features.features) AS features,
GROUP_CONCAT(plants_features.features_id) AS feature_ids
FROM plants_features
JOIN plants2features
ON plants_features.features_id = plants2features.features_id
JOIN plants
ON plants2features.plant_id = plants.plant_id
GROUP BY plants.plant_id, plants.scientific_name;
还使用JOIN
语法而不是逗号和where。