mysql 两个select合并,将两个mysql查询合并为一个

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".

EDIT

Additionally, I want the result to be returned in a single row. So that I can access the value in php eg

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

From Simon's suggestion, I should not use UNION because I want to return a single row of data

解决方案

You can't ORDER BY in your first SELECT and then UNION it.

Edit

You can however

apply ORDER BY or LIMIT to an individual SELECT, place the clause inside the parentheses that enclose the 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);

Which then makes your 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

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;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值