MYSQL按列表排序

时间:2012-12-31 15:16:09

标签: mysql sql select sql-order-by

我的表A有一个'ID'和'Message',另一个表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;

2 个答案:

答案 0 :(得分:0)

由于您按汇总Table B订购COUNT(),因此您可以在ORDER BY中使用相同的值。只需将其添加到导出SELECT的{​​{1}}列表中。

Table B

注意:如果您发布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 表的示例,我将使用SQLFiddle示例进行更新...

答案 1 :(得分:0)

试试这个:

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;