简体   繁体   English

具有条件的SQL内部联接

[英]SQL INNER JOIN with IF CONDITION

I have following SQL Statment 我有以下SQL语句

 Select 
      a.A,
      a.B,
      b.C
 FROM table a 
 INNER JOIN table b
 on (a.A =  b.A)
 WHERE a.A = @A

My problem is that when there is no A in table b matches the A in table a, all the A, BC, will not be showing. 我的问题是,当表b中没有A匹配表a中的A时,将不会显示所有的A,BC。 It works only when there is a value that meet aA = bA How could I get all A, B, and C even if if is not meet aA = bA I tried to use IF statement which is obviously not working.Thanks. 仅当存在一个满足aA = bA的值时,它才起作用。即使不满足aA = bA,我也如何获得所有A,B和C。我试图使用显然不起作用的IF语句。

SELECT
      a.A,
      a.B,
      b.C
 FROM table_a  a
 LEFT JOIN table_b b
 ON (a.A =  b.A)
 WHERE a.A = @A

Of course, you won't get anything from bC if the join condition doesn't match but you will get all rows in table a 当然,如果连接条件不匹配,您将无法从bC获得任何信息,但是您将获得表a中的所有行

If your really want ALL rows in both table_a and table_b, use a FULL OUTER JOIN instead. 如果您确实想要table_a和table_b中的所有行,请改用FULL OUTER JOIN。

Using a LEFT JOIN will get everything from your left table (table_a here) and if there is a matching record (dictated by your JOIN criteria) in the right table (table_b here) then the data from that table will be returned. 使用LEFT JOIN将从左侧表(此处为table_a)中获取所有内容,如果右侧表(此处为table_b)中存在匹配记录(由JOIN条件指示),则将返回该表中的数据。 If There is not a corresponding record in the right table for the record in the left table, then NULL will be returned for that/those column/s you are selecting from the right table. 如果右表中没有与左表中的记录相对应的记录,则将为您从右表中选择的那个/那些列返回NULL。

SELECT
    a.A,
    a.B,
    ISNULL(b.C, 'No Match In table_b')
FROM table_a a
LEFT JOIN table_b b
ON (a.A = b.A)
WHERE a.A = @A

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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