I have 2 tables, which represent one to many relationship
CREATE TABLE a( id int, a_text varchar(255) );
And
CREATE TABLE b( a_id int, b_text varchar(255) );
Where column b_text
contains enum values.
Table A:
Id | a_text |
---|---|
1 | ‘text 1’ |
2 | ‘text 2’ |
Table B:
a_id | b_text |
---|---|
1 | ‘status 1’ |
1 | ‘status 2’ |
2 | ‘status 1’ |
1 | ‘status 3’ |
I want to write a SELECT query with several b_text
values as parameters, that returns all rows from table a
, that contain only given b_text
values after join. For example, I want to get all rows from table a
that have only b_text
values status_1 and status_2. So row with id
=1 will be returned.
The question is:
Is there a way to write a common sql query, that does not depend of number of parameters?
I have a sollution, in which i just add new JOIN to b table with where statement for a speciffic value, but it doesn’t suit because there is no way to dynamically add a new join
3
Answers
You can use intersect:
OR you can use in:
If you are looking to match certain values between the two tables have you already tried a Left Join?
This will return only b_text with the values you indicated:
The straight-forward way to write the query is:
This means for every status you’ll have to add a condition with
AND
.If you want a query that does not change with the number of conditions, then the desired statuses must be stored in a separate table. The query could look like this then for instance:
Or, instead of a separate table you use a comma-separated list (e.g.
'status 1,status 2'
) along withFIND_IN_SET
.Demo: https://dbfiddle.uk/0dC-PbEQ