【发布时间】:2020-01-18 04:18:59
【问题描述】:
Select Date_format(effective_date, "%M %Y") as time
from articles
order by effective_date desc limit 10;
+----------------+
| time |
+----------------+
| November 2019 |
| November 2019 |
| September 2019 |
| September 2019 |
| August 2019 |
| July 2019 |
| June 2019 |
| May 2019 |
| April 2019 |
| March 2019 |
+----------------+
表结构
CREATE TABLE `articles` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`author_id` bigint(20) DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
`article_page_details_count` int(11) DEFAULT NULL,
`effective_date` datetime DEFAULT NULL,
`position` int(11) DEFAULT NULL,
`hits` int(11) DEFAULT NULL,
`status` int(11) DEFAULT '0',
`deleted_at` datetime DEFAULT NULL,
`created_by_admin_user_id` bigint(20) DEFAULT NULL,
`updated_by_admin_user_id` bigint(20) DEFAULT NULL,
`created_at` datetime NOT NULL,
`updated_at` datetime NOT NULL,
PRIMARY KEY (`id`),
KEY `index_articles_on_author_id` (`author_id`),
KEY `index_articles_on_created_by_admin_user_id` (`created_by_admin_user_id`),
KEY `index_articles_on_updated_by_admin_user_id` (`updated_by_admin_user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=113 DEFAULT CHARSET=utf8
我只想获取唯一记录。 distinct 不起作用,如果我使用 group by 则 order 不起作用。
mysql版本是8.0
with Distinct 我得到了错误。
Select distinct(Date_format(effective_date, "%M %Y")) as time
from articles
order by effective_date desc limit 10;
ERROR 3065 (HY000): ORDER BY 子句的表达式 #1 不在 SELECT 中 列表,引用列 'articles.effective_date' 不在 选择列表;这与 DISTINCT 不兼容
【问题讨论】:
-
DISTINCT将删除重复项,您所说的 不起作用 是什么意思? -
发布完整的表格数据和
SHOW CREATE TABLE articles...我假设effective_date不是唯一的列。这里接缝的主要问题是字符串的排序可能会产生不可预测的结果因为字符集/排序规则 -
请注意,
DISTINCT不是函数。无需使用括号.. -
使用这个Select distinct Date_format(effective_date, '%M %Y')
-
@PKP 订单与您的查询不符