【问题标题】:Running a query with PHP/MySQL then reordering the results by another column使用 PHP/MySQL 运行查询,然后按另一列重新排序结果
【发布时间】:2010-03-01 22:11:01
【问题描述】:

这个 SQL 查询给了我想要的结果;但是,我希望结果按不同的列排序:

SELECT * 
FROM post 
    INNER JOIN account ON post.account_id = account.account_id 
WHERE post_id > new 
ORDER BY post_date 
ASC LIMIT 10;

我不能简单地将ORDER BY post_date ASC 更改为ORDER BY post_id DESC,虽然这实际上会按照我想要的方式对查询进行排序...它会给我错误的 10 个帖子。

我只想获取上述查询的EXACT RESULTS,然后按post_id 对结果重新排序。
如果可能,我想使用 SQL 来执行此操作,否则我可以通过将结果添加到新的反转数组中来对结果进行排序。

【问题讨论】:

  • 您的查询应该失败,返回 MySQL 错误 1060: Duplicate column name because of the account_id 同时存在于两个表中。
  • 确实如此,我对数据库进行了一些更改,现在一切都像魅力一样,感谢您指出这一点!

标签: php sql mysql sql-order-by


【解决方案1】:

使用子查询重新排序:

SELECT * FROM (
  SELECT *
  FROM post
  INNER JOIN account ON post.account_id = account.account_id
  WHERE post_id > neww
  ORDER BY post_date ASC LIMIT 10;
) ORDER BY post_id

【讨论】:

  • 感谢工作就像一个魅力,我不敢相信我已经为此搜索了 2 天 :(...
  • 谢谢,我认为这将是解决我自己的问题的方法(在 SQL Server 2k8 上)。你已经为我确认了。 +1
  • 此查询缺少 AS,应为 ...) AS x ORDER BY post_id。见dev.mysql.com/doc/refman/5.7/en/from-clause-subqueries.html
【解决方案2】:

使用子查询:

SELECT * FROM (
    SELECT *
    FROM post
    INNER JOIN account
    ON post.account_id = account.account_id
    WHERE post_id > neww
    ORDER BY post_date ASC
    LIMIT 10) AS T1
ORDER BY post_id DESC

【讨论】:

  • 哇,注意这里发生的竞争条件。 (均于 3 月 1 日 22:13 发布)虽然两个答案都是正确的,但只有一个可以得到“正确”的答案。我觉得有趣的是,Mark 的答案将子查询命名为 T1,然后没有引用它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-16
  • 2018-09-27
  • 1970-01-01
  • 2017-07-25
  • 2016-03-02
  • 1970-01-01
相关资源
最近更新 更多