[英]Selecting distinct dates from datetime column in a table
I have a table 我有一张桌子
id | message | date_posted
1 | testing | 2011-03-08 03:15:13
2 | testing | 2011-03-06 03:15:13
3 | testing | 2011-03-08 03:15:13
And need a query where I return a list of distinct dates in desc order. 并且需要一个查询,我以desc顺序返回不同日期的列表。 I tried to formulate a query like so
我试着像这样制定一个查询
SELECT DISTINCT CAST(`date_posted` AS DATE) AS dateonly FROM table
This gives me dates but they're not distinct and have duplicates. 这给了我约会,但它们并不明显,并且有重复。
Any ideas? 有任何想法吗? (Using php/mysql)
(使用php / mysql)
MAJOR EDIT: 主要编辑:
Forgot an important piece of information. 忘了重要的一条信息。 I'm trying to get unique dates based on month and year.
我试图根据月份和年份获得独特的日期。
2011-03-08 03:15:13
2011-03-06 03:15:13
2011-03-02 03:15:13
2011-03-01 03:15:13
2011-02-01 03:15:13
So running the query would only return [2011-03-dd,2011-02-01] (dd being any day) 所以运行查询只会返回[2011-03-dd,2011-02-01](dd是任何一天)
Apologize for not stating this. 为没有说明这一点而道歉。
Your query will return unique DATES, as you've specified. 您的查询将返回您指定的唯一日期。 If you want to get just unique MONTHS/YEARS, you should either modify you dates in a way, that each date becomes the first day of the month, or you should just go with some string representation like 'YYYY-MM'.
如果你想获得唯一的MONTHS / YEARS,你应该以某种方式修改你的日期,每个日期成为一个月的第一天,或者你应该使用像'YYYY-MM'这样的字符串表示。 Sorry, I can't write you an exact code how to do this, as I do not develop on mysql, but I think this should get you somewhere :)
对不起,我不能写一个确切的代码如何做到这一点,因为我没有在mysql上开发,但我认为这应该让你在某处:)
SELECT DISTINCT YEAR(date_posted), MONTH(date_posted) FROM table
SELECT DATE(`date_posted`) AS dateonly
FROM table
GROUP BY DATE(`date_posted`)
Working example 工作实例
create table dts (dt datetime);
insert dts select '2011-03-08 03:15:13';
insert dts select '2011-03-07 03:15:13';
insert dts select '2011-03-09 03:15:13';
insert dts select '2011-03-08 03:15:13';
select distinct cast(dt as date) from dts;
Output 产量
"cast(dt as date)"
"2011-03-08"
"2011-03-07"
"2011-03-09"
Query for distinct Year-Month 查询不同的年月
select date(date_format(dt, '%Y-%m-1')) as dt
from dts
group by dt;
Output (the result is a date column, with the day set to '1') 输出(结果是日期列,日期设置为'1')
2011-03-01
SELECT DISTINCT date(date_format(COLUMN_NAME, '%Y-%m-%d')) as uniquedates from TABLE_NAME
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.