php 将两个mysql查询合二为一
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14281663/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Combine two mysql query into one
提问by PutraKg
What is the proper syntax to combine these two queries?
组合这两个查询的正确语法是什么?
SELECT clicks FROM clicksTable WHERE clicks > 199 ORDER BY clicks ASC LIMIT 1
and
和
SELECT clicks FROM clicksTable ORDER BY clicks DESC LIMIT 1
I tried:
我试过:
SELECT clicks FROM clicksTable WHERE clicks > 199 ORDER BY clicks ASC LIMIT 1
UNION
SELECT clicks FROM clicksTable ORDER BY clicks DESC LIMIT 1;
but I get "Incorrect usage of UNION and ORDER BY".
但我得到“UNION 和 ORDER BY 的错误使用”。
EDITAdditionally, I want the result to be returned in a single row. So that I can access the value in php eg
编辑另外,我希望结果在一行中返回。这样我就可以访问php中的值,例如
$row['nextclick'] and $row['topclick']
From Simon's suggestion, I should not use UNION because I want to return a single row of data
根据西蒙的建议,我不应该使用 UNION 因为我想返回单行数据
回答by Simon Martin
You can't ORDER BYin your first SELECTand then UNIONit.
你不能ORDER BY在你的第一个SELECT然后UNION它。
Edit
You can however
编辑
但是你可以
apply ORDER BY or LIMIT to an individual SELECT, place the clause inside the parentheses that enclose the SELECT:
将 ORDER BY 或 LIMIT 应用于单个 SELECT,将子句放在包含 SELECT 的括号内:
as in the 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);
Which then makes your SQL
然后让你的 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);
Edit 2
To return in an array
编辑 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;
回答by Hamlet Hakobyan
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;
回答by Gordon Linoff
First, do you want a unionor a union all?
首先,你想要 aunion还是 a union all?
The problem is the order byin the first part. You can fix this, using subqueries:
问题出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))
In a unionexpression, order byis only allowed at the end and it applies to the entire expression.
在一个union表达式中,order by只允许在最后,它适用于整个表达式。

