我想在同一列中创建sql req两次使用order我尝试使用此示例
public static void main(String[] args){
Student student1 = new Student();
但是sql错误表明UNION和ORDER BY的使用不正确
SELECT titleEN, smallDescriptionEN, StartDate, EndDate
FROM event
WHERE EndDate > NOW()
ORDER BY StartDate ASC
UNION
SELECT titleEN, smallDescriptionEN, StartDate, EndDate
FROM event
WHERE EndDate < NOW()
ORDER BY StartDate DESC
答案 0 :(得分:0)
最后一个Order By
足以订购完整的结果集
SELECT titleEN,
smallDescriptionEN,
StartDate,
EndDate
FROM event
WHERE EndDate < Now()
UNION
SELECT titleEN,
smallDescriptionEN,
StartDate,
EndDate
FROM event
WHERE EndDate > Now()
ORDER BY StartDate DESC;
答案 1 :(得分:0)
假设这只是一个例子,并且假设您的商业案例是合法的,那么这将完全符合您的要求:
DECLARE @tmpAsc AS TABLE (titleEN VARCHAR(MAX), smallDescriptionEN VARCHAR(MAX),
StartDate DATETIME, EndDate DATETIME)
INSERT INTO @tmpAsc
SELECT titleEN,
smallDescriptionEN,
StartDate,
EndDate
FROM [EVENT]
WHERE EndDate > GETDATE()
ORDER BY StartDate DESC
DECLARE @tmpDesc AS TABLE (titleEN VARCHAR(MAX), smallDescriptionEN VARCHAR(MAX),
StartDate DATETIME, EndDate DATETIME)
INSERT INTO @tmpDesc
SELECT titleEN,
smallDescriptionEN,
StartDate,
EndDate
FROM [EVENT]
WHERE EndDate < GETDATE()
ORDER BY StartDate DESC;
SELECT * FROM @tmpAsc
UNION ALL
SELECT * FROM @tmpDesc
答案 2 :(得分:0)
如前所述,联合查询只有一个ORDER BY子句。如果要对这种方式进行排序,则需要一个带有CASE结构的子句:
SELECT titleEN, smallDescriptionEN, StartDate, EndDate
FROM event
WHERE EndDate > NOW()
UNION ALL
SELECT titleEN, smallDescriptionEN, StartDate, EndDate
FROM event
WHERE EndDate < NOW()
ORDER BY
CASE WHEN EndDate > NOW() THEN 1 ELSE 2 END -- "after now" before "before now"
CASE WHEN EndDate < NOW() THEN StartDate ELSE NULL END DESC
CASE WHEN EndDate > NOW() THEN StartDate ELSE NULL END ASC;
或者简单地说:
select titleen, smalldescriptionen, startdate, enddate
from event
where enddate <> now()
order by (enddate < now()), abs(timestampdiff(second, now(), startdate)) desc;
日期/时间操作是特定于dbms的(就此而言是布尔表达式)。这适用于MySQL。