简体   繁体   English

有条件的MYSQL SELECT JOIN

[英]MYSQL SELECT JOIN with condition

I'm working on a tricky query and just don't understand how to approach it since neither JOIN gives me desirable result. 我正在处理一个棘手的查询,只是不了解如何处理它,因为两个JOIN都没有给我令人满意的结果。

I have two tables: 我有两个表:

Table1:
id
value

Tabel2:
id
table1_id
parameter (1,0)
value

I need to select everything from Table_1, but if there is a row in Table2 with table1_id = table1.id and parameter = 1, I want to include table2.value in the outcome. 我需要从Table_1中选择所有内容,但是如果Table2中有table1_id = table1.id且参数= 1的行,我想在结果中包括table2.value。 Note, that there can be multiple rows with table1_id = table1.id in Table2, but only one with parameter=1. 请注意,表2中可以有多行table1_id = table1.id,但只有一行参数== 1。

So, what I'm looking to get as aa result 所以,我希望得到的结果

table1.id | table1.value | table2.parameter |table2.value
    1     |      v1      |                  |      
    2     |      v1      |         1        |      v2
    3     |      v1      |                  |      
    4     |      v1      |         1        |      v2

Can someone help me with a query. 有人可以帮我一个查询。 Thank you for your time. 感谢您的时间。

SELECT *
FROM
  Table1 LEFT JOIN Table2
  ON (Table1.id = Table2.table1_id AND Table2.parameter = 1)
;

You can use left join and case when for showing the table2 value 您可以case when显示table2 value case when使用left joincase 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM