6

组合这两个查询的正确语法是什么?

SELECT clicks FROM clicksTable WHERE clicks > 199 ORDER BY clicks ASC LIMIT 1

SELECT clicks FROM clicksTable ORDER BY clicks DESC LIMIT 1

我试过:

SELECT clicks FROM clicksTable WHERE clicks > 199 ORDER BY clicks ASC LIMIT 1
UNION
SELECT clicks FROM clicksTable ORDER BY clicks DESC LIMIT 1;

但我得到“UNION 和 ORDER BY 的错误使用”。

编辑 此外,我希望结果在一行中返回。这样我就可以访问 php 中的值,例如

$row['nextclick'] and $row['topclick'] 

根据西蒙的建议,我不应该使用 UNION 因为我想返回单行数据

4

3 回答 3

16

你不能ORDER BY在你的第一个SELECT然后UNION它。

编辑
但是你可以

将 ORDER BY 或 LIMIT 应用于单个 SELECT,将子句放在括住 SELECT 的括号内:

如在MySQL UNION 文档中

(SELECT a FROM t1 WHERE a=10 AND B=1 ORDER BY a LIMIT 10)
UNION
(SELECT a FROM t2 WHERE a=11 AND B=2 ORDER BY a LIMIT 10);

然后让你的 SQL

(SELECT clicks FROM clicksTable WHERE clicks > 199 ORDER BY clicks ASC LIMIT 1)
UNION
(SELECT clicks FROM clicksTable ORDER BY clicks DESC LIMIT 1);

编辑 2
返回array

SELECT (SELECT clicks 
        FROM clicksTable 
        WHERE clicks > 199 
        ORDER BY clicks ASC 
        LIMIT 1) AS NextClick,
       (SELECT clicks 
        FROM clicksTable 
        ORDER BY clicks DESC 
        LIMIT 1) AS TopClick;
于 2013-01-11T15:49:50.187 回答
3
SELECT clicks FROM
    (SELECT clicks FROM clicksTable WHERE clicks > 199 ORDER BY clicks ASC LIMIT 1) A
UNION
SELECT clicks FROM
    (SELECT clicks FROM clicksTable ORDER BY clicks DESC LIMIT 1) B;
于 2013-01-11T15:49:54.620 回答
1

首先,你想要 aunion还是 a union all

The problem is the order by in the first part. You can fix this, using subqueries:

(select * from (SELECT clicks FROM clicksTable WHERE clicks > 199 ORDER BY clicks ASC LIMIT 1))
UNION ALL
(select * from (SELECT clicks FROM clicksTable ORDER BY clicks DESC LIMIT 1))

In a union expression, order by is only allowed at the end and it applies to the entire expression.

于 2013-01-11T15:51:09.507 回答