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?
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.
Yes, it is possible to use MySQL GROUP BY clause with multiple columns just as we can use MySQL DISTINCT clause.
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.
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.
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
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