我在mysql数据库中有2个表:
tbl_fruit(fruit_id,fruit_name):
fruit id | fruit_name
--------------------------
1 | Apple
2 | Banana
3 | Mango
tbl_order(order_id,order_name,fruit_id):
order_id | order_name | fruit_id
-----------------------------------
1 | John | 1,2
2 | Matt | 1,3
3 | Jessica | 1,2,3
预期产出:
order_name | selected_fruit
----------------------------------
John | Apple, Banana
Matt | Apple, Mango
Jessica | Apple, Banana, Mango
我尝试了一些查询但是没有达到预期的输出效果。 提前谢谢。
求助:
SELECT
order_name,
(select
GROUP_CONCAT(fruit_name SEPARATOR ', ')
from tbl_fruits as fru
where
FIND_IN_SET (fru.fruit_id,ord.fruit_id)) as selected_fruit
FROM `tbl_order` as ord
答案 0 :(得分:1)
嗯,你可以做到,但这并不意味着你应该这样做。您可以在子查询中使用find_in_set()连接2个表,然后在外部查询中使用group_concat()来获取结果:
select t.order_name, group_concat(t.fruit_name) as selected_fruits
from
(select o.order_name, f.fruit_name
from `order` o inner join fruit f on find_in_set(f.fruit_id, o.fruit_id)) t
group by t.order_name
答案 1 :(得分:0)
请尝试以下查询。使用内部查询和GROUP_CONCAT。
SELECT order_name,(select GROUP_CONCAT( fruit_name SEPARATOR ',' ) from tbl_fruit as fru where FIND_IN_SET (fru.fruit_id,ord.fruit_id)) as selected_fruit FROM `tbl_order` as ord
请尝试让我知道。
答案 2 :(得分:0)
试试这个。在使用ist进行JOIN之前,必须拆分arg。此示例适用于最多3个水果,但您可以展开它。
docker run -it --rm -w /opt/maven \
-v $PWD:/opt/maven \
-v $HOME/.m2:/root/.m2 \
maven:3.3-jdk-8 \
mvn clean install
<强>结果强>
SELECT o.order_name, CONCAT_WS(', ', arg1.fruit_name, arg2.fruit_name, arg3.fruit_name ) AS selected_fruit
FROM tbl_order o
LEFT JOIN tbl_fruit arg1 ON arg1.fruit_id = SUBSTRING_INDEX( SUBSTRING_INDEX(CONCAT(o.fruit_id,',,,'),',',1) ,',', -1)
LEFT JOIN tbl_fruit arg2 ON arg2.fruit_id = SUBSTRING_INDEX( SUBSTRING_INDEX(CONCAT(o.fruit_id,',,,'),',',2) ,',', -1)
LEFT JOIN tbl_fruit arg3 ON arg3.fruit_id = SUBSTRING_INDEX( SUBSTRING_INDEX(CONCAT(o.fruit_id,',,,'),',',3) ,',', -1);
如果有效,请告诉我