【问题标题】:Sorting relational tables using only 1 field in mysql仅使用 mysql 中的 1 个字段对关系表进行排序
【发布时间】:2021-01-13 16:36:38
【问题描述】:

我有 2 个关系表,我加入了它们,我希望它按相同的字段排序。

表格:

帖子字段:id、post、created

转发字段:id、post_id、created

这是我目前拥有的:

SELECT 
p.post as post,
p.created as post_created,
rp.created as repost_created
FROM posts p
LEFT JOIN reposts rp
ON rp.post_id = p.id
ORDER BY rp.created DESC, p.created DESC

这是该代码的结果:

{1

但我想要的是对整个数据进行排序,基于 created 字段作为一个整体,关于它是否有 repost_created 或者它是否为空,它将基于在 post_created 字段上。像这样:

[2

非常感谢!

【问题讨论】:

  • 您不会在任一图像中显示 p.id 或 rp.post_id,但您可能需要在 order by 子句中包含两者。例如order by coalece(rp.post_id, p.id) 然后是其他列。如果您在问题中提供了示例数据(以文本形式,按表格,而不是查询结果),那么也许我们可以做更多

标签: mysql sql sorting join sql-order-by


【解决方案1】:

看起来您只需要将rp.created 的值与p.created 合并,然后对其进行排序;这样,如果 rp.created 不为 NULL,您将按该日期排序,否则您将按 p.created 排序:

ORDER BY COALESCE(rp.created, p.created) DESC

请注意,您可能需要一个额外的标准来打破平局(当两行具有相同的日期时间值时),您也许可以使用

ORDER BY COALESCE(rp.created, p.created) DESC, rp.id IS NULL

这将同时在帖子之前对转发进行排序。

【讨论】:

  • 非常感谢,这正是我想要的。对不起,如果我的问题不是很清楚,但感谢您理解我的问题并回答它的努力?
  • @sonson 不用担心 - 我很高兴能帮上忙。
【解决方案2】:

我认为你的目的是

SELECT 
p.post as post,
p.created as post_created,
rp.created as repost_created
FROM posts p
LEFT JOIN reposts rp
ON rp.post_id = p.id
ORDER BY  isnull( p.created ,rp.created)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-27
    相关资源
    最近更新 更多