[英]How do I order this UNION MySQL Query?
I have the following query and want to order the results by the CREATED column, how would I go about doing it? 我有以下查询,并希望按CREATED列排序结果,我该怎么做呢?
(SELECT media.id, media.accessKey, media.internalName, media.type, media.modified, users.username, users.id, media.created,
0 AS reposted
FROM media
LEFT JOIN users ON users.id = media.userId)
UNION
(SELECT media.id, media.accessKey, media.internalName, media.type, media.modified, users.username, reposts.userId, reposts.created,
1 AS reposted
FROM reposts
LEFT JOIN media ON media.id = reposts.mediaId
LEFT JOIN users ON users.id = reposts.userId)
Add: 加:
order by created
At the end of your query. 在查询结束时。
You just need to add the order by clause to your query (the use of (
around the queries is not mandatory): 您只需要将order by子句添加到查询中(使用
(
在查询周围不是必需的):
SELECT media.id,
media.accessKey,
media.internalName,
media.type,
media.modified,
users.username,
users.id,
media.created,
0 AS reposted
FROM media
LEFT JOIN users ON users.id = media.userId
UNION
SELECT media.id,
media.accessKey,
media.internalName,
media.type,
media.modified,
users.username,
reposts.userId,
reposts.created,
1 AS reposted
FROM reposts
LEFT JOIN media ON media.id = reposts.mediaId
LEFT JOIN users ON users.id = reposts.userId
ORDER BY CREATED ASC
You can check this sqlfiddle to see it working. 您可以检查此sqlfiddle以查看它是否正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.