我一直很好奇是否有更好的方法来做到以下几点:
假设我有一张鞋子待售,有一些耐克,阿迪达斯,特瓦,史蒂夫马登 等。
CREATE TABLE Shoes(
id int not null auto_increment primary key,
brand int not null, /* NIKE: 1, ADIDAS: 2, TEVA: 4, STEVE_MADDEN: 8 */
quality int not null /* NEW: 1, USED: 2*/
price datetime not null,
posted timestamp default current_timestamp
);
现在我希望看到给定品牌的最低和最高价格以及质量。所以 这就是我所拥有的,但我想知道是否有更好的方法来考虑 一个非常大的数据库。
让我们说我想知道NIKE鞋子(新的和二手的)的最高和最低价格我 会做以下事情:
SELECT MIN(price) AS lowest, MAX(price) AS highest FROM Shoes WHERE brand = 1 AND quality = 1;
SELECT MIN(price) AS lowest, MAX(price) AS highest FROM Shoes WHERE brand = 1 AND quality = 2;
有更好的方法吗?
答案 0 :(得分:1)
您可以使用一个查询执行此操作,并返回2行和一个字段。
SELECT quality, MIN(price) AS lowest,
MAX(price) AS highest
FROM Shoes
WHERE
brand = 1
AND
quality IN(1,2)
GROUP BY quality
ORDER BY quality;
加入示例
SELECT quality, MIN(s.price) AS lowest,
MAX(s.price) AS highest,
t.OneField
FROM Shoes s
LEFT JOIN YourTable t ON s.brand = t.TheBrandField
WHERE
s.brand = 1
AND
s.quality IN(1,2)
GROUP BY s.quality
ORDER BY quality;