WHERE statement after a UNION in SQL?

后端 未结 3 989
挽巷
挽巷 2020-12-12 23:29

How do I apply a WHERE statement after a UNION in SQL/MySQL?

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-13 00:04

    If you want to apply the WHERE clause to the result of the UNION, then you have to embed the UNION in the FROM clause:

    SELECT *
      FROM (SELECT * FROM TableA
            UNION
            SELECT * FROM TableB
           ) AS U
     WHERE U.Col1 = ...
    

    I'm assuming TableA and TableB are union-compatible. You could also apply a WHERE clause to each of the individual SELECT statements in the UNION, of course.

提交回复
热议问题