SQL filtering by multiple columns

前端 未结 3 1303
旧时难觅i
旧时难觅i 2021-01-13 07:24

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:

<         


        
相关标签:
3条回答
  • 2021-01-13 07:48

    A rough but practical way is to use string concatenation:

    SELECT *
    FROM MyTable
    WHERE CONCAT(f1, '_', f2) IN ('a_30', 'b_20')
    
    0 讨论(0)
  • 2021-01-13 08:02
    SELECT * FROM my_table WHERE (f1= 'a' AND f2=30) OR (f1='b' AND f2=20);
    
    0 讨论(0)
  • 2021-01-13 08:07

    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
    
    0 讨论(0)
提交回复
热议问题