选择上一个日期和将来的所有日期

时间:2014-04-05 13:01:13

标签: mysql

我只想选择过去最近的日期和将来的所有日期。

我使用以下查询得出结果,但结果是并排而不是每行。

我应该如何修改我的查询?

SELECT t1.*, t2.*
FROM
    (SELECT *
        FROM table1
     WHERE from_p <= NOW()
        AND prod = 3000
     ORDER BY from_p DESC
     LIMIT 1) AS t1
JOIN
    (SELECT *
        FROM table1
     WHERE from_p >= NOW()
        AND prod = 3000
     ORDER BY from_p DESC
    ) AS t2

2 个答案:

答案 0 :(得分:1)

您需要使用子查询来首先找到&#34;最新的过去日期&#34;然后根据以下内容编写主查询:

SELECT * FROM table1 
WHERE from_p >= (
    SELECT from_p FROM table1 
    WHERE from_p <= NOW() AND prod=3000
   ORDER BY from_p DESC LIMIT 1
    )
    AND prod=3000 
ORDER BY from_p;

答案 1 :(得分:0)

尝试:

(SELECT *
    FROM table1
 WHERE from_p <= NOW()
    AND prod = 3000
 ORDER BY from_p DESC
 LIMIT 1)
UNION
 (SELECT *
    FROM table1
 WHERE from_p >= NOW()
    AND prod = 3000
 ORDER BY from_p DESC)