[英]MYSQL SELECT JOIN with condition
我正在處理一個棘手的查詢,只是不了解如何處理它,因為兩個JOIN都沒有給我令人滿意的結果。
我有兩個表:
Table1:
id
value
Tabel2:
id
table1_id
parameter (1,0)
value
我需要從Table_1中選擇所有內容,但是如果Table2中有table1_id = table1.id且參數= 1的行,我想在結果中包括table2.value。 請注意,表2中可以有多行table1_id = table1.id,但只有一行參數== 1。
所以,我希望得到的結果
table1.id | table1.value | table2.parameter |table2.value
1 | v1 | |
2 | v1 | 1 | v2
3 | v1 | |
4 | v1 | 1 | v2
有人可以幫我一個查詢。 感謝您的時間。
SELECT *
FROM
Table1 LEFT JOIN Table2
ON (Table1.id = Table2.table1_id AND Table2.parameter = 1)
;
您可以case when
顯示table2 value
case when
使用left join
和case when
select
t1.id,
t1.value,
t2.parameter,
case when t2.table_id is not null and t2.parameter = 1 then t2.value else null end as table2_value
from table1 t1
left join table2 t2 on t2.table1_id = t1.id
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.