[英]SQL. Count rows where 2 columns foreigns is same type
我有這樣的任務,我無法解決。
我有這些表:
users:
id | type
transactions:
id | sender_id | receiver_id
我該如何select
才能為每個交易行生成此結果:
id | sender_id | receiver_id | sender_type | receiver_type
嘗試JOIN
但沒有成功,我只得到sender_id
, receiver_id
, type
。
我怎樣才能兩次獲得type
列?
例如:
users:
id | type
1 | 4
2 | 3
3 | 1
4 | 3
transactions:
id | sender_id | receiver_id
1 | 2 | 3
2 | 1 | 4
3 | 3 | 1
result:
id | sender_id | receiver_id | sender_type | receiver_type
1 | 2 | 3 | 3 | 1
2 | 1 | 4 | 4 | 3
3 | 3 | 1 | 1 | 4
您需要為每種類型(發送者和接收者)顯式加入用戶表,例如:
SELECT
tr.id,
tr.sender_id,
tr.receiver_id,
us_sn.type,
us_rx.type
FROM
transactions tr
JOIN
users us_rx ON tr.receiver_id = us_rx.id
JOIN
users us_sn ON tr.sender_id = us_sn.id
為此,您需要的技巧是將users
表兩次 JOIN
到transactions
表中。
您將需要別名來執行此操作。 我使用了一個字母的別名r
和s
。 這是JOIN操作的非常普遍的應用。 就像表有兩個副本一樣工作。
它也有助於為列名創建別名。 當您使用重復的列名稱來提供結果集時,某些SQL客戶端的工作方式會很奇怪。
SELECT t.id, t.sender_id, t.receiver_id,
s.type sender_type,
r.type receiver_type
FROM transactions t
JOIN users s ON t.sender_id = s.id
JOIN users r ON t.receiver_id = r.id
ORDER BY t.id
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.