PHP / MySQL用于计算具有相同外键的项之间的差异

时间:2017-09-21 15:00:31

标签: php mysql sql select

我有一个表items,其中列idname和一个表ratingsiditemid,{{1} }。我想要做的是返回结果,其中具有相同rating的两个评级之间的差异是最大的,按降序排列。

1 个答案:

答案 0 :(得分:2)

您可以从最低评级中减去最高评级,并按顺序排序:

SELECT   i.*
FROM     items i
JOIN     (SELECT   itemid, MAX(rating) - MIN(rating) AS diff
          FROM     ratings
          GROUP BY itemid) r ON i.id = r.itemid
ORDER BY diff DESC