我有一个包含价格和主类别列的产品表。
我想查询我的数据库以查找给定类别(或所有类别)的价格范围。然后将这个价格范围分成适当数量的价格范围,即0-5英镑、5-10英镑等...
我无法理解如何做到这一点;我需要用 php 做这一切吗?
编辑:经过深思熟虑,澄清一下,我想结束,这样无论列出什么类别,我都可以显示大概 4 个价格范围,每个价格范围内的产品数量大致相等。我无法解决这个问题:(
对于每个类别的最低和最高价格:
SELECT category, min(price) as min_price, max(price) as max_price
from Products
Group BY category
对于直接在查询中的范围,您可以执行以下操作
SELECT
category,
SUM(CASE WHEN price BETWEEN 0 AND 5 THEN 1 ELSE 0 END) as zero-five,
SUM(CASE WHEN price BETWEEN 5 AND 10 THEN 1 ELSE 0 END) as five-ten,
...
from Products
Group BY category
产量
Category zero-five five-ten
Cat1 2 4
Cat2 3 6
或者
SELECT category, range, count(*)
FROM (
SELECT
category,
CASE WHEN price BETWEEN 0 to 5 THEN '0-5'
WHEN price BETWEEN 5 to 10 THEN '5-10'
...
ELSE '10+'
END as range
FROM products
)
group by category, range
产量
Category range count
Cat1 0-5 2
Cat1 5-10 4
Cat1 10+ 0
Cat2 0-5 3
Cat2 5-10 6
Cat2 10+ 0
$sql = "
SELECT P1.category as category, min(P1.price) as min_price, max(P2.price) as max_price
FROM Products P1 join Products P2 on P1.category=P2.category
Group BY category
";
<table width="300" border="1">
<tr>
<td><b>category</b></td>
<td><b>min_price</b></td>
<td><b>max_price</b></td>
</tr>
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
//print data
?>
<tr>
<td><? echo $row['category']; ?></td>
<td><? echo $row['min_price']; ?></td>
<td><? echo $row['max_price']; ?></td>
</tr>
<?
}
?>
不确定您的表结构,但这将在您的产品表中获取独特的价格:
select distinct price from products order by price desc;
从这里开始,我可能会开始使用 PHP。您究竟希望如何将这些价格分成几组?