Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inner join for a query?

Tags:

sql

mysql

I want to do a sql query and have some problems:

  1. I want to select from table_1 the ID's Where parent_id is the value I have:

    SELECT ID 
      FROM table_1 
     WHERE parent_ID = 'x'
    
  2. I want to use the ID'S I got in 1. and

    SELECT 
      FROM table_2 
     WHERE ID = 'The ID's from Query 1.'
    
like image 330
Christina Avatar asked Jul 30 '26 22:07

Christina


1 Answers

Like this?

select ...
  from table_1 a
  join table_2 b on(a.id = b.id)
 where a.parent_id = 'x';

Edit
Note: the query will potentially produce duplicate rows depending on the keys and relation between the tables. For example, you will get duplicates if, for a given table_1.parent_id = X, there can be multiple occurrences of the same table_1.ID. Another example is when table_2.ID isn't unique.

In those cases you would want to remove the duplicates (using distinct, group by, partitioned @row_number, etc) or, not produce the duplicates in the first place using a semi-join instead (exists, in). Have a look @OMG Ponies answer for reference.

like image 193
Ronnis Avatar answered Aug 01 '26 11:08

Ronnis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!