mysql连接问题

标签 mysql join

table a
-------------------------------------------------
id   name     wishlist1    wishlist2     wishlist3

1    john      1              2            3
2    paul      4              5


table b
--------------------------------------------------
id    goods

1     car
2     aircraft
3     bicycle
4     motorbike
5     ipad


result i want to get
---------------------------------------------------
john    car        aircraft    bicycle
paul    motorbike  ipad

我怎么能得到这个结果? (在 mysql 中)

最佳答案

这最多输出 3 个愿望(当他们没有愿望时,愿望列中为空)

select
  name,
  g1.goods as wish1,
  g2.goods as wish2,
  g3.goods as wish3
from tablea a
left join tableb g1.id on g1.wishlist1
left join tableb g2.id on g1.wishlist2
left join tableb g3.id on g1.wishlist3

不过,如果您不介意以逗号分隔的愿望列表,这可能会更好,而且更整洁:

select
  name,
  group_concat(goods) as wishes
from tablea a
left join tableb b on b.id in (a.wishlist1, a.wishlist2, a.wishlist3)
group by name;

将输出:

name  |  wishes
------|----------------------
john  |  car,aircraft,bicycle
paul  |  motorbike,ipad

关于mysql连接问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6786974/

相关文章:

连接数据的 MySQL 条件

mysql - wampserver 2.5 mysql数据位置没有改变

php - 以正确的方式处理高流量

mysql - 如何循环遍历 MySQL 中的行并根据下一行的值插入数据?

mysql - 嵌套循环连接中的磁盘 block 读取数

mysql - 如何在需要连接的两个表中查询特定类型的电影名称?

hibernate - FetchMode Join与SubSelect

php - PHP 数量更新仅影响一行

mysql - 自定义 mysql alpine 镜像未从作为卷安装的 docker-entrypoint-initdb.d 加载 init.sql

PHP/mySQL 连接 - 结果中有多个重复行