[英]Joining SELECT of two rows with same id in SQL
好吧,我有這張桌子
| 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可以嗎?
我已經嘗試過使用分組依據,但是我不知道如何使用它
而且我不知道在Google中使用哪個詞來搜索解決我的問題的方法
我只有一張桌子
這樣的事情應該起作用-
select
t1.first,
t1.last,
t2.first,
t2.last,
t1.type
from
test t1
inner join test t2
on t1.id = t2.id
and t1.type = 'bill'
and t1.type != t2.type
實際上,您所需要做的就是在同一張表上執行內部聯接
嘗試類似
select bill.id, bill.first, bill.last, ship.first, ship.last
from t as bill, t as ship
where bill.id = ship.id
and bill.type = 'bill'
and ship.type = 'ship'
或者,您可以使用Join使其更具現代感。
SELECT b.id, b.first, b.last, s.first, s.last
FROM bill b
LEFT JOIN ship s ON b.id=s.id AND b.type='bill' AND s.type='ship'
嘗試這個:
SELECT A.id,A.first, A.last,
B.first, B.last
FROM T2 A
INNER JOIN T2 B
ON A.id = B.id
AND A.type = 'bill'
AND B.type = 'ship'
您可以使用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不支持full outer join
,因此使用join
很難處理這種情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.