php – 将两个mysql查询合并为一个

前端之家收集整理的这篇文章主要介绍了php – 将两个mysql查询合并为一个前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

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,因为我想返回一行数据

最佳答案
您不能在第一个SELECT中进行ORDER BY,然后UNION它.

编辑
但是你可以

apply ORDER BY or LIMIT to an individual SELECT,place the clause inside the parentheses that enclose the SELECT:

如在MySQL UNION documentation

(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
要返回数组

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;
原文链接:https://www.f2er.com/mysql/434096.html

猜你在找的MySQL相关文章