Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySql SET intersection

Tags:

mysql

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!

like image 750
Tin Avatar asked Sep 05 '12 08:09

Tin


People also ask

How do you set an intersection in MySQL?

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.

What is set intersection in SQL?

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.

What can I use instead of INTERSECT in MySQL?

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.

How do I INTERSECT two columns in SQL?

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.


1 Answers

Why not use OR ?

SELECT * FROM mydb WHERE FIND_IN_SET(2, numbers) or FIND_IN_SET(4, numbers) 
like image 132
sel Avatar answered Nov 05 '22 05:11

sel