我使用了以下查询,但显示错误。
SELECT
id as number,id,parentid,videoid,subject,name,created,message
FROM
umqlh_hdflv_comments
WHERE
`parentid` = '0'
AND `published` = '1'
AND `videoid` = '8'
ORDER BY
number DESC,
parentid
UNION (
SELECT
parentid as number,id,parentid,videoid,subject,name,created,message
FROM
umqlh_hdflv_comments
WHERE
`parentid` != '0'
AND `published` = '1'
AND `videoid` = '8'
)
MySQL说:文档
#1221 - Incorrect usage of UNION and ORDER BY
如何解决此问题?
答案 0 :(得分:1)
ORDER BY
需要在完整的sql语句结束时应用
SELECT
id as number,
id,
parentid,
videoid,
subject,
name,
created,
message
FROM
umqlh_hdflv_comments
WHERE
`parentid` = '0'
AND `published` = '1'
AND `videoid` = '8'
UNION (
SELECT
parentid as number,
id,
parentid,
videoid,
subject,
name,
created,
message
FROM
umqlh_hdflv_comments
WHERE
`parentid` != '0'
AND `published` = '1'
AND `videoid` = '8'
)
ORDER BY number DESC,parentid
答案 1 :(得分:0)
从语法上讲,您需要将订单移动到查询结尾。除了优化之外,例如"限制"在联合中订购其中一个零件是没有意义的,因为无论如何都不能保证对结果进行分类。
SELECT id as number
,id
,parentid
,videoid
,subject
,name
,created,message
FROM umqlh_hdflv_comments
WHERE `parentid` = '0'
AND `published` = '1'
AND `videoid` = '8'
UNION
SELECT parentid as number
,id
,parentid
,videoid
,subject
,name
,created,message
FROM umqlh_hdflv_comments
WHERE `parentid` != '0'
AND `published` = '1'
AND `videoid` = '8'
ORDER BY number DESC,parentid
但是,此查询也可以表示为:
SELECT case when parentid = 0 then id else parentid end as number
,id
,parentid
,videoid
,subject
,name
,created,message
FROM umqlh_hdflv_comments
WHERE `published` = '1'
AND `videoid` = '8'
ORDER BY number DESC,parentid
如果parentid可以为null,则需要在where子句中添加parentid不为null。此外,如果行不是唯一的(我假设这个,因为列被命名为id),您需要为查询添加distinct以使其等效。