选择按另一个表行排序的行

时间:2017-11-24 08:09:00

标签: php mysql sql select mysqli

我们称这个表为CATEGORIES:

           +---------+-------
           | id  | name     | 
           +-----+----------|
           |   1 | CATEG 1  |
           |   2 | CATEG 2  |
           |   3 | CATEG 3  |
           |   4 | CATEG 4  |



           And this is Items:
           +----+-------------+---------------+--------
           | id |    name     |  categoryid   | price |
           +----+-------------+---------------+--------
           |  1 |  Book       |       2       |   5$  |
           |  3 |  Toy Car    |       1       |   8$  |
           |  2 |  Pencil     |       2       |   3$  |
           |  4 |  Toy Box    |       1       |   2$  |
           |  5 |  BookCase   |       2       |   4$  |
           |  6 |  Barbie     |       1       |   7$  |
           +----+-------------+---------------+-------+ 

如何按料品价格从表格顺序中选择类别?我是否需要两个查询,或者我可以使用连接语句?

1 个答案:

答案 0 :(得分:1)

这样的事可能有效

 select c.id, sum(price) category_price
 from categories c
 left join items i on c.id = i.categoryid
 group by c.id
 order by category_price