MySQL查询的ORDER BY和GROUP BY

时间:2012-02-14 15:18:37

标签: mysql

我有两个mySQL表如下:

[product] table
P_id | Name | Quantity
1    | B    | 10
2    | C    | 15
3    | A    | 8

[attribute] table 
P_id | Name  | Quantity
1    | Black | 5
1    | Red   | 5
2    | Blue  | 6
2    | Black | 9

如何编写SQL查询,以便它可以显示上述两个表的结果,如下所示: 报告:

P_id | Name  | Quantity
3    | A     | 8
1    | B     | 10
1    | Black | 5
1    | Red   | 5
2    | C     | 15
2    | Black | 9
2    | Blue  | 6

这些应该在[Name]列上排序,但这些应该在P_id列上进行分组,如上所述。通过在P_id上“分组”,我的意思是“保持所有记录具有相同的P_id彼此相邻”。是否可以使用单个SQL查询检索上述排列。

6 个答案:

答案 0 :(得分:3)

SELECT P_id, Name, Quantity FROM (
  SELECT P_id, Name, Quantity, Name as parent, 1 as level
    FROM product
  UNION
  SELECT a.P_id, a.Name, a.Quantity, p.Name as parent, 2 as level
    FROM attribute a JOIN product p ON a.P_id = p.P_id
) combined ORDER BY parent, level, Name

答案 1 :(得分:0)

它应该是联盟操作,我相信这样:

select * from product union select * from attribute order Name;

不确定为什么你写道你需要`group by'因为您的输出没有按任何列分组。

答案 2 :(得分:0)

你的意思是你只需要两个表的联合吗? 你可以试试这个:

Select P_id, Name, Quantity
From product

Union

Select P_id, Name, Quantity
From attribute

Order by 2

答案 3 :(得分:0)

SELECT * FROM 
(
   SELECT P_id, Name , Quantity FROM product
   UNION ALL
   SELECT P_id, Name , Quantity FROM attribute
) Order by Name

答案 4 :(得分:0)

你必须使用我的朋友分组。然后,您可以在 Both 上订购所需的列,如下所示:

SELECT * FROM product UNION SELECT * FROM attribute ORDER BY Name, P_id;

答案 5 :(得分:0)

如果您希望它们按P_id排序,然后按名称排序,这应该可以。

(SELECT P_id, Name, Quantity FROM product)
UNION
(SELECT P_id, Name, Quantity FROM attribute)
ORDER BY P_id, Name;