简体   繁体   中英

SQL join query with conditions

Table IMAGE I'm a beginner in SQL and need help with the below pls. I need to compare table1 and table2 and display matching IDs as output if present in both tables. If not present in table 2 should display null. Output should display values for one single day and version. Thanks in advance

Table 1

|ID |TDate      |Tversion|
 :-  :---------  :------- 
|1  |05-03-2022 |0.1     | 
|1  |05-03-2022 |0.2     |
|1  |04-03-2022 |0.1     |
|1  |04-03-2022 |0.2     |
|2  |05-03-2022 |0.1     |
|2  |05-03-2022 |0.2     |
|2  |04-03-2022 |0.1     |
|2  |04-03-2022 |0.2     |
|3  |05-03-2022 |0.1     |
|3  |05-03-2022 |0.2     |
|3  |04-03-2022 |0.1     |
|3  |04-03-2022 |0.2     |


Table 2 :

|ID |DDate     |   |Dversion|
 :-  :---------     :------
|1  |05-03-2022|   |  1     |
|1  |05-03-2022|   |  2     |
|1  |04-03-2022|   |  1     |
|1  |04-03-2022|   |  2     |
|2  |05-03-2022|   |  1     |
|2  |05-03-2022|   |  2     |
|2  |04-03-2022|   |  1     |
|2  |04-03-2022|   |  2     |


Output : 

|Table 1.ID |Table2.ID|        |Date       |
 :---------  :--------          :----------
|1          |1        |        | 05-03-2022|
|2          |2        |        | 05-03-2022|
|3          |NULL     |        | 05-03-2022|
  

Future, edit your existing post, and put actual sample data WITHIN your posted questions, not images. As for the query, what you would be looking for is a LEFT JOIN. Meaning, I want all records from a left-side (first table listed) regardless of a matching record on the right-side (second) based on whatever the common key. That said, it would be something like

select
      t1.id,
      t1.id tbl2ID,
      t2.ddate
   from
      Table1 t1
         LEFT JOIN Table2 t2
            on t1.id = t2.id
           AND t1.tdate = t2.ddate
   where
      t1.tdate = '2022-05-03'

Again, not having your table structure listed, and going by a bad image which you could have done a print-screen even. This should get what you are looking for. Notice that Table1 is the left table (first one listed in the query) LEFT JOINed to the right table (second one) based on whatever the common ID between them.

The selected columns, just pull whatever the columns of interest are. The "t1" and "t2" are just aliases vs writing what could be long table names repeatedly in longer and more complex queries. Or even using the same table multiple times in the same query for different purposes / conditions.

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