简体   繁体   中英

SQL how to load all relevant rows from table A based on a value from the table B

I have a large data set, which should be loaded in chunks, the query below runs but it returns only the first instances (rows) from table A, while I need all rows from table A that have a specified value in the base column of table B.

select * 
from table A as a 
where a.base in (select b.base 
                 from
                     (select
                          row_number() over() AS rn, * 
                      from
                          "folder2"."table B" ) as b
                 where 
                     rn between 5 and 10)

Table A

base    col2    co3
---------------------
 777    kjh    nbvm
 111    sd     dsf
 111    fs     cx
 222    xcv    bc
 222    gfd    xcb
 222    xcv    cxb

Table B

base
------
000
777
888
999
444
111
222
333
444
555

The query above returns this result:

asin    col2    co3
--------------------
 111    sd      dsf
 222    xcv     bc

When I need the result in full:

base    col2    co3
--------------------
 111    sd      dsf
 111    fs      cx
 222    xcv     bc
 222    gfd     xcb
 222    xcv    cxb

Thanks a lot for the help

I have created those two tables without 777 id in table b and do the sql as follwos:

SELECT a.* 
  FROM table_a a, table_b b
 WHERE a.base = b.base

where it gives the result:

base    col2    col3
111     sd      dsf
111     fs      cx
222     xcv     bc
222     gfd     xcb
222     xcv     cxb

This seems to be a typical case of INNER JOIN as the INNER JOIN keyword selects records that have matching values in both tables.

SELECT A.* FROM A INNER JOIN B on A.base = b.base

You should use an INNER JOIN to join table A with B and then a ORDER BY to get the output in the order you want.

SELECT A.base as asin, a.col2, a.col3
FROM A
INNER JOIN B ON A.base = b.base
ORDER BY A.base

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