I have next database
| ID | numbers |
|--------|------------|
| 1 | 1,2,3 |
| 2 | 4,5,6 |
| 3 | 2,3,4 |
To retrieve all rows where numbers
holds a given number is easy:
SELECT * FROM mydb WHERE FIND_IN_SET(3, numbers)
This returns row 1 and 3
But now I want to pass an array/set of numbers and want to retrieve all entries where at least one number occurs in numbers
, i.e. where the intersect of both sets is not empty
Something like:
SELECT * FROM mydb WHERE SET_INTERSECT('2,4', numbers)!=NULL
This should return all rows because every row holds 2 and/or 4.
The above doesn't work. Is this possible in mysql?
Thanks!
Syntax : SELECT column1,column2,columnn FROM table1 [WHERE condition] INTERSECT SELECT column1,column2,columnn FROM table1 [, table2 ] [WHERE condition]; Example : Consider the two tables as follows.
The INTERSECT clause in SQL is used to combine two SELECT statements but the dataset returned by the INTERSECT statement will be the intersection of the data-sets of the two SELECT statements. In simple words, the INTERSECT statement will return only those rows which will be common to both of the SELECT statements.
SELECT category_id FROM products INTERSECT SELECT category_id FROM inventory; Since you can't use the INTERSECT operator in MySQL, you will use the IN operator to simulate the INTERSECT query as follows: SELECT products.
Similar to the UNION operator in SQL, even the INTERSECT operator has to abide by the following two rules for successful execution: The number and order of columns in both queries has to be the same. The data types of corresponding columns from both the select queries must be compatible with each other.
Why not use OR ?
SELECT * FROM mydb WHERE FIND_IN_SET(2, numbers) or FIND_IN_SET(4, numbers)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With