【问题标题】:MYSQL Order By ListMYSQL 按列表排序
【发布时间】:2012-12-15 17:01:57
【问题描述】:

我有一个表 A,它有一个“ID”和“消息”,另一个表 B 是有序的。我希望根据表 B 中的排序方式订购表 A。

示例 - 表 A:

ID    Message
-------------
1     ABC
2     DEF
3     HIJ
4     KLM
5     NOP

表 B:

ID
---
5
2
4
1
3

预期结果:

ID    Message
-------------    
5     NOP
2     DEF
4     KLM
1     ABC
3     HIJ

我有以下疑问:

SELECT DISTINCT s.message, s.stream_id
FROM Stream s
ORDER BY ..... ;

我该怎么做? 显然使用 FIND_IN_SET 没有考虑表 B 的顺序

更新

表 B 的排序如下:

SELECT stream_id 
FROM SearchCache 
GROUP BY stream_id 
ORDER BY COUNT(stream_id);

因此,查询应该如下所示:

SELECT DISTINCT s.message, s.stream_id
FROM Stream s
ORDER BY s.stream_id *SOMETHING* (SELECT stream_id 
                                  FROM SearchCache 
                                  GROUP BY stream_id 
                                  ORDER BY COUNT(stream_id)) ASC;

【问题讨论】:

  • Table B 是如何排序的?它似乎没有任何特定的顺序,并且您无法按照插入的顺序可靠地检索行...
  • 从表B中选择时如何指定顺序?如果您没有为表 B 指定 ORDER BY,那么答案是如果不指定 ORDER BY,您将无法可靠地确定行的输出顺序。
  • @Travesty3 伟大的思想都一样,嗯?
  • tableb 上有主键吗?
  • 所以Table BINSERT INTO SELECT 的结果还是只是一个查询?

标签: mysql sql select sql-order-by


【解决方案1】:

由于您通过聚合 COUNT() 订购 Table B,因此您可以在 ORDER BY 中使用相同的值。只需将其添加到派生Table BSELECT 列表中。

SELECT
  DISTINCT 
  s.message, 
  s.stream_id
FROM 
  Stream s
  /* Join against a subquery that produces a count per stream_id */
  /* Using LEFT JOIN in case none exist for a given s.stream_id */
  LEFT JOIN (
    SELECT stream_id, COUNT(*) AS num_streams
    FROM SearchCache
    GROUP BY stream_id
   ) stream_counts ON s.stream_id = stream_counts.stream_id
/* Order by the COUNT() aggregate supplied by the joined subquery */
ORDER BY stream_counts.num_streams ASC

注意:如果您发布 SearchCache 表的示例,我将使用 SQLFiddle 示例进行更新...

【讨论】:

    【解决方案2】:

    试试这个:

    SELECT a.id, a.message 
    FROM tablea a 
    INNER JOIN (SELECT (@auto:=@auto+1) auto, id 
                FROM tableb, (SELECT @auto:=0) AS a) AS b ON a.id = b.id 
    ORDER BY b.auto;
    

    【讨论】:

      猜你喜欢
      • 2010-10-05
      • 2012-06-07
      • 1970-01-01
      • 2016-07-19
      • 2018-03-12
      • 2012-10-19
      相关资源
      最近更新 更多