mysql - Order by 子句不适用于此查询

标签 mysql sql sql-order-by

CREATE TABLE `cc_comment_master` (
  `ID` int(11) DEFAULT NULL,
  `DRAFT_SALESDOC_HEADER_ID` int(11) DEFAULT NULL,
  `PRODUCT_ID` int(11) DEFAULT NULL,
  `PRODUCT_NUMBER` varchar(50) DEFAULT NULL,
  `COMMENT_DESC` varchar(100) DEFAULT NULL,
  `COMMENT_BY` varchar(50) DEFAULT NULL,
  `COMMENT_ON` datetime DEFAULT NULL,
  `MODIFIED_BY` varchar(100) DEFAULT NULL,
  `MODIFIED_ON` datetime DEFAULT NULL,
  `CREATED_BY` varchar(100) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


insert  into `cc_comment_master`(`ID`,`DRAFT_SALESDOC_HEADER_ID`,`PRODUCT_ID`,`PRODUCT_NUMBER`,`COMMENT_DESC`,`COMMENT_BY`,`COMMENT_ON`,`MODIFIED_BY`,`MODIFIED_ON`,`CREATED_BY`) 
values (1,1,1,'abc','first','test','2016-01-12 10:43:48','test',NULL,'test'),(2,2,2,'def','second','test','2016-01-12 10:43:53','test',NULL,'test'),(3,3,3,'xyz','third','test','2016-01-12 10:43:56','test',NULL,'test'),(4,4,4,'pqr','four','test','2016-01-12 10:44:33','test',NULL,'test');

查询:

declare @comments  varchar(max)
set @comments = ''

Select 
    @comments = @comments +''+ COMMENT_DESC+'-COMMENT_SEPERATOR-' 
from 
    CC_COMMENT_MASTER c 
where 
    c.DRAFT_SALESDOC_HEADER_ID = 1
    and PRODUCT_NUMBER = 'abc'
order by 
    c.COMMENT_ON  desc   --order by not working 

select @comments;

我想选择一个字符串中附加的所有 COMMENT_DESC,按 COMMENT_ON 降序排列。

如果没有 order by 子句,我将在一个字符串中按 asc 顺序获取所有 COMMENT_DESC。当我尝试通过 COMMENT_ON desc 订购时,它不起作用。

输出:

first-COMMENT_SEPERATOR-

预期输出:

first-COMMENT_SEPERATOR-second-COMMENT_SEPERATOR-third--COMMENT_SEPERATOR-

错误:

The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP or FOR XML is also specified.

最佳答案

试试这个

declare @comments  varchar(max)
set @comments = ''

Select 
    @comments =  @comments +''+ COMMENT_DESC+'-COMMENT_SEPERATOR-' 
from 
    (select top 100 percent * from CC_COMMENT_MASTER c  order by COMMENT_ON  desc) as t 

select @comments;

关于mysql - Order by 子句不适用于此查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34736224/

相关文章:

sql - 根据具体情况选择

sql - 如何在 postgres 中截断时间戳中的秒数?

sql - 合并来自两个不同列的两个对象数组,以在 postgresql 中创建一个新的唯一且非空对象数组

mysql - GROUP BY ORDER BY 帮助

mysql - 我应该将用户上传的照片存储在哪里?

php - 如何避免 CakePHP View 中出现 html 实体?

django - 编程错误 : when using order_by and distinct together in django

MySQL:在不划分集合的情况下对有序行的集合进行排序

MySql Select - 行减去上一行

mysql - 如何分组并显示结果 sun 到 sat,MySQL PHP