postgresql - SQL query for join table and multiple values -
so have 3 tables involved in problem, 2 regular tables , join table has many , belongs many relationship. this:
table1 --id --data table2 --id --data table1_table2 --table1_id --table2_id so, question how query (using join) have 1 or more values in table1_table2 1 item in table1. instance:
table 1 +----------+ |id | data | +----------+ |1 | none | +----------+ |4 | match| +----------+ table 2 +----------+ |id | data | +----------+ |1 | 1 | +----------+ |2 | 2 | +----------+ table1_table2 +----------------------+ |table1_id | table2_id | +----------------------+ |1 | 1 | +----------------------+ |4 | 1 | +----------------------+ |4 | 2 | +----------------------+ i need query match table 1 row id 4 because has link via join both row 1 , 2 table 2. if confusing please ask anything.
maybe bit unclear, using table1_table2 join not from. need make sure matches 1 , 2 both table 2.
here query far...
select distinct table1.id, table2.data table1 left join table1_table2 on table1.id = table1_table2.table1_id left join table2 on table2.id = table1_table2.table2_id i need make entry in table 1 matches both 1 , 2 table 2.
the output looking be:
+---------------------+ |table1.id|table2.data| +---------------------+ |4 |one | +---------------------+ |4 |two | +---------------------+
the following approach works if can guarantee there no duplicates in table1_table2 table. maybe can start here , finesse bit. note how join condition works -- putting in in join condition works differently if put in condition in clause.
i've used hash marks values need have code insert sql.
select table1.id, count(table1_table2.table2_id) table1 join table1_table2 on (table1_table2.table1_id = table1.id , table1_table2.table2_id in (#somelist#)) group table1.id having count(table1_table2.table2_id) = (#length of somelist#) oops -- you've changed question in way suggested , i've ignored edit. should started, returns table1 id's interested in.
Comments
Post a Comment