Using tuples in SQL “IN” clause

前端 未结 8 1092
刺人心
刺人心 2020-11-28 04:30

I have a table containing the fields group_id and group_type and I want to query the table for all the records having any tuple (group id, group type) from

相关标签:
8条回答
  • 2020-11-28 04:48

    EDIT: this is a dated answer, although it was the accepted answer in 2011, other answers with more upvotes reflect more recent approaches.

    Why not construct the OR statements?

    SELECT *
    FROM mytable 
    WHERE (group_id = '1234-567' and group_type = 2)
        OR (group_id = '4321-765' and group_type = 3)
        OR (group_id = '1111-222' and group_type = 5)
    

    Granted, it doesn't look as nice and neat as your concept example but it will do the job (and if you IN with tuples did exist, it would implement it exactly the same way under the covers most likely.

    0 讨论(0)
  • 2020-11-28 04:51

    Here is another tuple solution using a join:

    SELECT 
      *
    FROM mytable m
    JOIN
    (
       SELECT "1234-567" group_id, 2 group_type 
       UNION ALL SELECT "4321-765", 3 
       UNION ALL SELECT "1111-222", 5
    ) [t]
    ON m.group_id = t.group_id 
    AND m.group_type = t.group_type
    
    0 讨论(0)
  • 2020-11-28 04:57

    In SQL Server 2008 you can do like this:

    select *
    from mytable as T
    where exists (select *
                  from (values ('1234-567', 2), 
                               ('4321-765', 3), 
                               ('1111-222', 5)) as V(group_id, group_type)
                  where T.group_id = V.group_id and
                        T.group_type = V.group_type               
                 )
    
    0 讨论(0)
  • 2020-11-28 04:57

    You can use a common table expression to pretend that these tuples are in another table:

    ;WITH Tuples as (
         select '1234-567' as group_id, 2 as group_type union all
         select '4321-765', 3 union all
         select '1111-222', 5
    )
    SELECT * /* TODO - Pick appropriate columns */
    from mytable m where exists (
       select * from Tuples t
       where m.group_id = t.group_id and m.group_type = t.group_type)
    
    0 讨论(0)
  • 2020-11-28 04:58
    select * from table_name where 1=1 and (column_a, column_b) in ((28,1),(25,1))
    
    0 讨论(0)
  • 2020-11-28 05:07

    Using that solution, this should work:

    SELECT *
    FROM mytable m
    WHERE EXISTS (
       SELECT * FROM (
       SELECT "1234-567" group_id, 2 group_type UNION ALL
       SELECT "4321-765", 3 UNION ALL
       SELECT "1111-222", 5) [t]
       WHERE m.group_id = t.group_id AND m.group_type = t.group_type) 
    

    BTW, you should probably use a CTE to create that inner table.

    0 讨论(0)
提交回复
热议问题