简体   繁体   中英

T-SQL Select all from TableA and condition on TableB

TableA Columns: A_ID, NAME, SOURCE, TITLE, EVENTID
TableB Columns: B_ID, EVENTID, CODE, FIELD

How do I extract NAME, SOURCE, TITLE and FIELD or null (if there is CODE=x) ? Example should show it better. It's T-SQL on SQL Server Express.

Example:

TableA                                 |   TableB
-----------------------------------------------------------------------
A_ID, NAME, SOURCE, TITLE, EVENTID     |   B_ID, EVENTID, CODE, FIELD
-----------------------------------------------------------------------
1     john  s1      x      100         |   1     100      5     textA  
2     bruce s2      y      105         |   2     100      10    textB
3     bob   s3      z      110         |   3     105      5     textC
                                       |   4     110      5     textD
                                       |   5     110      10    textE

There is no code 10 for EventId 105 so the result should be null. How do write a SELECT quesry that would give me such result:

[ john  | s1 | x | textB ]
[ bruce | s2 | y |       ]
[ bob   | s3 | z | textE ]

It might be really easy but I can't figure it out.. Thanks in advance.

You need an OUTER JOIN between the tables

SELECT A.NAME,
       A.SOURCE,
       A.TITLE,
       B.FIELD
FROM   TableA A
       LEFT JOIN TableB B
         ON A.EVENTID = B.EVENTID
            AND B.CODE = 10  

The B.CODE = 10 condition needs to go in the JOIN not a WHERE clause to avoid effectively turning the query back into an INNER JOIN .

This can return multiple rows for a particular A value if there is more than one joining record but it is not clear from your question if this is possible in your data anyway (and if so which B.Field value should be used) and this may well be your desired behaviour.

This should do it

SELECT a.NAME, a.SOURCE, a.TITLE, b.FIELD 
  FROM TableA a
       LEFT JOIN TableB b ON b.EventId = a.EventId
             AND b.Code = 10

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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