0

在我的数据库中有 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
4

1 回答 1

1
SELECT
  products.title
FROM
  products INNER JOIN ratings
  ON products.id = ratings.id
GROUP BY
  products.id,
  products.title
ORDER BY
  SUM(ratings.rating='l')-SUM(ratings.rating='d')

在此处查看小提琴。

如果您还想显示排名编号,您可以使用以下命令:

SELECT @rank:=@rank+1 as rank, title
FROM (
  SELECT
    products.title
  FROM
    products INNER JOIN ratings
    ON products.id = ratings.id
  GROUP BY
    products.id,
    products.title
  ORDER BY
    SUM(ratings.rating='l')-SUM(ratings.rating='d')
  ) s, (SELECT @rank:=0) r

小提琴在这里

于 2013-07-04T08:16:49.797 回答