简体   繁体   中英

Sql Join selecting records from A table and selecting matching records with a condition from B table

We have Table A and Table B, Data we need is in table A and we use table B to validate case where we have matching Ids. If ids do not match we can select it without validation, but if they match we need to check if date is in between date1 and date2. We only check records in B if they have match in A; (fe we can neglect id=4 in table B because its not in A); And we only need data from A table.

I spent too much time to create the sql to select:

Everything from Table A that is not in the table B (ids, fe id=1,3), and select matching records where matching records A.date is between B.date1 and B.date2 (if its matching and not in between dont select)

TABLE A
id       date          col1
1       5/08/2021    11223344
2       15/06/2021   22334411
2       15/04/2021   22223344 
3       10/11/2021   22223311

TABLE B
id       date1         date2
5       5/08/2021     5/09/2021
2       15/05/2021    15/07/2021
2       15/08/2021    15/09/2021
4       15/08/2021    15/10/2021

The result should look like this:

id       date          col1
1       5/08/2021    11223344
3       10/11/2021   22223311
2       15/06/2021   22334411

An improvemed to your question, would be to add your last try at a query. But from what I understood, your problem can be solved like this:

SELECT A.ID, A.date, A.col1 FROM A
LEFT JOIN B ON A.id = B.id
WHERE (A.Date BETWEEN B.date1 AND b.date2) OR B.date1 IS NULL
  • LEFT JOIN to keep all records of table A
  • A.Date BETWEEN B.date1 AND b.date2 to filter matching rows according to your condition
  • B.Date1 IS NULL for rows from A without an match in B

Because you want to keep all rows in A that meet your conditions -- presumably with no duplicates -- I would suggest using exists and `not exists:

select a.*
from a
where exists (select 1
              from b
              where a.id = b.id and
                    a.date between b.date1 and b.date2
             ) or
      not exists (select 1
                  from b
                  where a.id = b.id
                 );

A solution using left join could return duplicate rows, if there are multiple matching rows in b .

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