组合这两个查询的正确语法是什么?
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']
根据Simon的建议,我不应该使用UNION,因为我想返回一行数据
答案 0 :(得分:14)
您的第一个ORDER BY
然后SELECT
不能UNION
。
修改强>
但是你可以
一样将ORDER BY或LIMIT应用于单个SELECT,将子句放在括起SELECT的括号内:
(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;
答案 1 :(得分: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;
答案 2 :(得分:1)
首先,您想要union
还是union all
?
问题是第一部分中的order by
。您可以使用子查询修复此问题:
(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))
在union
表达式中,order by
仅在结尾处被允许,并且它适用于整个表达式。