只用id(MYSQL)获取不同的日期

时间:2016-03-08 12:41:31

标签: mysql sql

我正在尝试在table shopping_t上获取不同的日期及其ID,我已尝试使用 distinct ,但由于某种原因,它会给我一个错误

SELECT 
guest_id,  shopping_date
FROM
shopping_t
WHERE
(shopping_date BETWEEN NOW() - INTERVAL 3 MONTH AND NOW())
order by
guest_id

上面的代码给了我

0   2016-01-02
0   2016-01-03
0   2016-01-05
0   2016-01-02 <-- result that I don't need
1   2016-01-02
1   2016-01-03
1   2016-01-08
1   2016-03-08
2   2016-01-02
2   2016-01-03
2   2016-01-08
2   2016-03-08

我想要的输出是

0   2016-01-02
0   2016-01-03
0   2016-01-05
1   2016-01-02
1   2016-01-03
1   2016-01-08
1   2016-03-08
2   2016-01-02
2   2016-01-03
2   2016-01-08
2   2016-03-08

我尝试过使用distinct,但我不知道为什么它会给我一个错误

SELECT 
guest_id, distinct(shopping_date)
FROM
shopping_t
WHERE
(shopping_date BETWEEN NOW() - INTERVAL 3 MONTH AND NOW())
order by
guest_id

我一直在寻找近一个小时的解决方案

2 个答案:

答案 0 :(得分:0)

distinct不是一个功能。 distinctselect上的修饰符。所以,试试:

SELECT DISTINCT guest_id, shopping_date
FROMshopping_t
WHERE (shopping_date BETWEEN NOW() - INTERVAL 3 MONTH AND NOW())
ORDER BY guest_id;

这假定shopping_date没有时间成分。如果它确实有时间组件,则提取日期,例如使用date()函数:

SELECT DISTINCT guest_id, DATE(shopping_date) as shopping_date
FROMshopping_t
WHERE shopping_date BETWEEN NOW() - INTERVAL 3 MONTH AND NOW()
ORDER BY guest_id;

答案 1 :(得分:0)

试试这个

SELECT guest_id, shopping_date
FROM shopping_t
WHERE (shopping_date BETWEEN NOW() - INTERVAL 3 MONTH AND NOW())
group by shopping_date,guest_id
ORDER BY guest_id;