What does the SQL standard say about parentheses in SQL UNION/EXCEPT/INTERSECT statements?

后端 未结 3 353
被撕碎了的回忆
被撕碎了的回忆 2021-01-18 19:15

I\'m trying to write a SQL UNION that works on both MySQL and SQLite.

(select_clause_A) UNION (select_clause_B)

SQLite doesn\'t like the pa

相关标签:
3条回答
  • 2021-01-18 19:36

    You can do this in SQLite:

     select col1, col2.. from ( select col1, col2 from T  order by col1 limit 5)
     union
     select col1, col2.. from ( select col1, col2 from T  order by col2 desc limit 10)
    

    Not sure about mySQl.

    0 讨论(0)
  • 2021-01-18 19:38

    The parens should not be required for MySQL, and from what I can tell reading the spec are not supposed to be there.

    MySQL is also nonstandard in that it supports an ORDER BY in each "part" of the union, so if you're writing it for non-MySQL you can't do that anyway.

    0 讨论(0)
  • 2021-01-18 19:54

    There's no need for brackets/parenthesis in a UNION statement.

    MySQL is the only one I'm aware of at this moment, which allows you to define ORDER BY and LIMIT clauses specific to each query as long as the query is enclosed in brackets -- standard SQL only allows a ORDER BY for the final result. The GROUP BY and HAVING clauses are specific to each query that makes up the UNION'd statement.

    MySQL supports:

     (SELECT a.column
        FROM A_TABLE a
    ORDER BY a.column DESC)
    UNION
    SELECT b.column
      FROM B_TABLE b
    

    ...which will cause no end of grief if you want/need to port to other databases.

    Standard SQL only allows:

    SELECT a.column
      FROM A_TABLE a
    UNION
    SELECT b.column
      FROM B_TABLE b
    ORDER BY column DESC
    
    0 讨论(0)
提交回复
热议问题