多个查询合二为一?

时间:2012-08-04 10:59:48

标签: mysql sql database

如何将此放入一个查询中?

例如:

SELECT * FROM `result` WHERE status = 'new' AND YEAR(`end_date`)  = '2012' limit 20
SELECT * FROM `result` WHERE status = 'new' AND YEAR(`end_date`)  = '2013' limit 20
SELECT * FROM `result` WHERE status = 'new' AND YEAR(`end_date`)  = '2014' limit 20
SELECT * FROM `result` WHERE status = 'new' AND YEAR(`end_date`)  = '2015' limit 20

SELECT * FROM `result` WHERE status = 'new' AND DAY(`end_date`)  = '1' limit 20
SELECT * FROM `result` WHERE status = 'new' AND DAY(`end_date`)  = '2' limit 20
... and to 31

and same for the Month Jan to Dec

基本上显示每天,每月和每年的20条记录。

3 个答案:

答案 0 :(得分:3)

您可以使用UNION以这种方式合并结果集:

SELECT * FROM `result` WHERE status = 'new' AND YEAR(`end_date`)  = '2012' limit 20
UNION
SELECT * FROM `result` WHERE status = 'new' AND YEAR(`end_date`)  = '2013' limit 20
UNION
SELECT * FROM `result` WHERE status = 'new' AND YEAR(`end_date`)  = '2014' limit 20
UNION
SELECT * FROM `result` WHERE status = 'new' AND YEAR(`end_date`)  = '2015' limit 20
UNION
SELECT * FROM `result` WHERE status = 'new' AND DAY(`end_date`)  = '1' limit 20
UNION 
SELECT * FROM `result` WHERE status = 'new' AND DAY(`end_date`)  = '2' limit 20
ORDER BY submit_date DESC

答案 1 :(得分:1)

我认为您需要使用存储的功能,而不是像这样可以帮助您

create function MyRecords()
RETURNS @MyResultsTable table
BEGIN
    select * into @MyResultsTable from ? where ?
    select * into @MyResultsTable from ? where ?
    select * into @MyResultsTable from ? where ?
    select * into @MyResultsTable from ? where ?
    .....
    .....
    .....
end

我现在没有安装MySql,但你应该尝试从控制台创建它并调用它。祝你好运!

答案 2 :(得分:-1)

SELECT * FROM `result` WHERE status = 'new' AND YEAR(`end_date`)  >= '2012' AND YEAR(`end_date`) <= '2015' AND DAY(`end_date`)  >= '1' AND DAY(`end_date`)  <= '32' AND  MONTH(`end_date`)  >= '1' AND  MONTH(`end_date`)  <= '12'  limit 20

这样做,你想要什么?