将两个mysql查询合并为一个

时间:2013-01-11 15:48:03

标签: php mysql sql database union

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

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

3 个答案:

答案 0 :(得分:14)

您的第一个ORDER BY然后SELECT不能UNION

修改
但是你可以

  

将ORDER BY或LIMIT应用于单个SELECT,将子句放在括起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
要以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仅在结尾处被允许,并且它适用于整个表达式。