MySQL 'multiple rows' 来自两个连接挑战
MySQL 'multiple rows' from two joins challenge
我有以下 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' 在一条记录中包含多行吗?
提前致谢,
理查德.
您需要分组和 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
语法代替逗号和位置。
我有以下 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' 在一条记录中包含多行吗?
提前致谢, 理查德.
您需要分组和 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
语法代替逗号和位置。