我有以下表格:
items(itemid, itemName, catid)
categories (catid, catname)
prices (itemid, open_price, close_price)
如果我有10个类别,每个类别包含10个项目(例如),我如何找到每个类别中价格变化最大的公司。
我目前有一个运行的php循环并获得每个类别的最佳表现,但是想知道是否有办法更有效地完成它。
由于
代码:
foreach category, run the following query:
SELECT c.itemid, c.itemname ,
100.0 * ( cp.close_price - cp.open_price )/ IFNULL(cp.open_price,1) AS overall_change
FROM prices cp
LEFT JOIN items c ON c.itemid = prices.itemid
WHERE c.catid=8 ORDER BY overall_change DESC LIMIT 1;
答案 0 :(得分:0)
如果你没有精神抽奖(当两个项目是一个类别的顶部时)
SELECT
cat.catid,
cat.catname,
c.itemid,
c.itemname ,
100.0 * ( cp.close_price - cp.open_price )/ IFNULL(cp.open_price,1) AS overall_change
FROM
categories AS cat
JOIN
items AS c
ON cat.catid = c.catid
JOIN
prices AS cp
ON c.itemid = cp.itemid
JOIN
(SELECT
c.catid,
MAX(100.0 * ( cp.close_price - cp.open_price )/ IFNULL(cp.open_price,1)) AS overall_change
FROM
items AS c
JOIN
prices AS cp
ON c.itemid = cp.itemid
GROUP BY
c.catid
) AS max
ON cat.catid = c.catid
AND max.overall_change = (100.0 * ( cp.close_price - cp.open_price )/ IFNULL(cp.open_price,1))
ORDER BY
cat.catid
......我还没有测试过这个:)