Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL filtering by multiple columns

Tags:

sql

mysql

I have a MySql table, which I want to query for rows in which pairs of columns are in a specific set. For example, say my table looks like this:

id | f1  | f2
-------------    
1  | 'a' | 20
2  | 'b' | 20
3  | 'a' | 30
4  | 'b' | 20
5  | 'c' | 20

Now, I wish to extract rows in which the pair (f1, f2) are either ('a',30) or ('b', 20), namely rows 2,3,4. I also wish to do it using an 'IN' style filter, as I may have many pairs to fetch. If I try something like:

SELECT * FROM my_table WHERE f1 IN ('a','b') AND f2 IN (30, 20)

I get the Cartesian product of the values specified for f1 and f2 in the IN clauses, i.e. the rows with all possible combinations for f1 = 'a' or 'b', and f2 = 30, 20, hence row 1 is also selected.

In short, I'm need something like:

SELECT * FROM my_table WHERE (f1,f2) IN (('a',30), ('b',20))

only with a valid SQL syntax :-)

Any ideas?

like image 937
bavaza Avatar asked Dec 20 '10 09:12

bavaza


People also ask

How do I search for multiple columns in SQL?

To select multiple columns from a table, simply separate the column names with commas! For example, this query selects two columns, name and birthdate , from the people table: SELECT name, birthdate FROM people; Sometimes, you may want to select all columns from a table.

Can I GROUP BY 3 columns in SQL?

Yes, it is possible to use MySQL GROUP BY clause with multiple columns just as we can use MySQL DISTINCT clause.

How do I sort 3 columns in SQL?

Syntax: SELECT * FROM table_name ORDER BY column_name; For Multiple column order, add the name of the column by which you'd like to sort records first.

How do I select multiple columns based on condition in SQL?

When we have to select multiple columns along with some condition, we put a WHERE clause and write our condition inside that clause. It is not mandatory to choose the WHERE clause there can be multiple options to put conditions depending on the query asked but most conditions are satisfied with the WHERE clause.


1 Answers

That is valid syntax.

If you don't like it some other alternatives are:

SELECT * FROM my_table
WHERE (f1, f2) = ('a', 30)
OR    (f1, f2) = ('b', 20)

Or using a join:

SELECT *
FROM my_table T1
(
    SELECT 'a' AS f1, 30 AS f2
    UNION ALL
    SELECT 'b', 20
) T2
ON T1.f1 = T2.f1 AND T1.f2 = T2.f2
like image 177
Mark Byers Avatar answered Oct 03 '22 14:10

Mark Byers