MySQL显示整个组,在组内按字母顺序排序

时间:2013-08-08 18:14:47

标签: mysql

我有以下查询:

SELECT * 

FROM vendors_parts INNER JOIN 

vendors ON vendors_parts.vendor = vendors.vendor_id

WHERE (vendors_parts.vendor = @vendor_id) AND (vendors_parts.active = @active) OR

(vendors_parts.vendor = @vendor_id) AND (vendors_parts.active = @inactive)

ORDER BY vendors_parts.old_id, vendors_parts.vendor_part, date_start DESC, vendors_parts.active DESC

以下列格式返回数据:

vendor_part      active       old_id
b                1            1
a                0            1
a                0            1
b                0            1
x                1            3
z                1            5
c                1            20
c                0            20

我的问题是在排序vendor_part升序和活动降序时如何将old_id保持在一起?我想要的输出是:

vendor_part      active       old_id
b                1            1
a                0            1
a                0            1
b                0            1
c                1            20
c                0            20
x                1            3
z                1            5

我还尝试过在old_id上分组的子查询,但这限制了我只有一个唯一的old_id:

SELECT *

FROM 
     (
     SELECT * FROM vendors_parts INNER JOIN vendors ON vendors_parts.vendor = vendors.vendor_id
     WHERE (vendors_parts.vendor = @vendor_id) AND (vendors_parts.active = @active) OR (vendors_parts.vendor = @vendor_id) AND (vendors_parts.active = @inactive)
     GROUP BY vendors_parts.old_id
     ) temp_table
ORDER BY vendor_part

如何将所有old_ids组合在一起,并按其各自组中的vendor_part按字母顺序排序?

谢谢

1 个答案:

答案 0 :(得分:0)

这是一个可能的答案。请注意,在这个答案中,表tbl是一个占位符,用于实际(相当复杂)的查询(我不喜欢使用它,但您可能必须使用临时表来保持查询语法的可管理性):

SELECT tbl.* FROM tbl 
  JOIN (SELECT MIN(vendor_part) as mvp, old_id FROM tbl GROUP BY old_id) as driver
  USING (old_id)
  ORDER BY driver.mvp, tbl.old_id, active DESC, tbl.vendor_part

有关实时演示,请参阅http://sqlfiddle.com/#!2/c53a9/4。正如您将看到的,使用您在问题中提供的示例,它会产生预期结果。