按比例排序 - MySQL

时间:2013-07-04 04:49:13

标签: mysql group-by sql-order-by

在我的数据库中有2个表:

产品表:

---------------
 id  |  title
---------------
 1     Toyoto
 2     Lexux

评级表:

----------------------------------------
rating_id  | rating | id | ip
----------------------------------------
     1          l      1    127.0.0.1
     2          d      1    127.0.0.2
     3          l      1    192.168.0.1
     4          l      2    192.168.0.1
-----------------------------------------

所以Toyoto有2 l(喜欢)和1 d(不喜欢)。所以我想根据喜欢和不喜欢对所有产品进行排序(总结喜欢和不喜欢)。在最后一个输出中将是:

Toyouto 3 votes and  Lexux 1 vote.

订单:

1. Toyoto
2. Lexux

1 个答案:

答案 0 :(得分:2)

你的查询应该是这样的

Select title,count(r.rating) as votes 
from product as p Inner join rating as r on p.id=r.id 
where r.rating=1 
group by r.id`