好的,我有这张 table
| id | first | last | type
1 mp de bill
1 mark ve ship
2 dw her bill
2 dwi rra ship
现在我希望它是这样的
| id | bill.first | bill.last | ship.first | ship.last
1 mp de mark ve
2 dw her dwi rra
连接行的主要关键是通过它们的 ID 这可能吗?
我已经尝试过使用 group by 但我不知道如何使用它
而且我不知道在谷歌中使用什么词来搜索我的问题的解决方案
我只有一张 table
最佳答案
您可以使用 group by
和条件聚合来做到这一点:
select id,
max(case when type = 'bill' then first end) as "bill.first",
max(case when type = 'bill' then last end) as "bill.last",
max(case when type = 'ship' then first end) as "ship.first",
max(case when type = 'ship' then last end) as "ship.last"
from table t
group by id;
对于您的情况,这会产生与 join
完全相同的结果。但是,如果给定值有多行,那么每个 id 仍只会生成一行。使用 max()
它将给出其中一行的一个值。使用 group_concat()
它将给出所有值。
这种方法的一个优点是它将包含所有 ID,即使某些 ID 缺少“账单”记录而其他 ID 缺少“发货”记录。不幸的是,MySQL 不支持完全外部连接
,因此使用连接
s 更难处理这种情况。
关于mysql - 在 SQL 中加入具有相同 ID 的两行的 SELECT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23080978/