您可能需要至少三种结果格式:
- 每个尺寸一行,但仅限于 10 种不同的产品
- 10 行 - 每个产品一个,一列包含逗号分隔的尺寸
- 两个结果集,将在 PHP 中组合:
对于每种格式,您需要以某种方式返回 10 种符合您条件的不同产品。
最有表现力的方式是使用 EXISTS 语句:
select p.*
from products p
where p.category = 'shoes'
and exists (
select *
from products_sizes ps
where ps.product_id = p.product_id
and ps.size = 10
)
order by p.product_id
limit $limit offset $offset
另一种方法是使用 JOIN:
select p.*
from products p
join products_sizes ps
on ps.product_id = p.product_id
where p.category = 'shoes'
and ps.size = 10
order by p.product_id
limit $limit offset $offset
由于其紧凑的代码,我将进一步使用第二个。但是你总是可以用 EXISTS 语句替换它。
1.
select p.*, ps.size
from (
select p.*
from products p
join products_sizes ps
on ps.product_id = p.product_id
where p.category = 'shoes'
and ps.size = 10
order by p.product_id
limit $limit offset $offset
) p
join products_sizes ps
on ps.product_id = p.product_id
order by p.product_id, ps.size
2.
select p.*, group_concat(ps.size order by ps.size) as sizes
from products p
join products_sizes ps1
on ps1.product_id = p.product_id
join products_sizes ps
on ps.product_id = p.product_id
where p.category = 'shoes'
and ps1.size = 10
group by p.product_id
order by p.product_id
limit $limit offset $offset
您可以使用explode()
PHP 将字符串转换为数组:
$product->sizes = explode(',' $product->sizes);
3.
select p.*
from products p
join products_sizes ps
on ps.product_id = p.product_id
where p.category = 'shoes'
and ps.size = 10
limit $limit offset $offset
将结果存储在按产品 ID 索引的数组中。例如在 fetchAssoc 循环中:
$row->sizes = array();
$products[$row->product_id] = $row;
从结果中提取产品 ID:
$productIds = (',', array_keys($products));
获取相关尺寸;
select product_id, size
from products_sizes
where product_id in ($productIds)
order by product_id, size
在循环中链接尺寸
$products[$row->product_id]->sizes[] = $row->size;
给定以下示例数据
| product_id | name | category | sizes |
|------------|--------|----------|-------|
| 1 | shoes1 | shoes | 8,9 |
| 2 | shirt1 | shirts | 10,11 |
| 3 | shoes2 | shoes | 9,10 |
| 4 | shoes3 | shoes | 10,11 |
| 5 | shoes4 | shoes | 10,12 |
并使用LIMIT 2 OFFSET 0
,结果将是:
1.
| product_id | name | category | size |
|------------|--------|----------|------|
| 3 | shoes2 | shoes | 9 |
| 3 | shoes2 | shoes | 10 |
| 4 | shoes3 | shoes | 10 |
| 4 | shoes3 | shoes | 11 |
2.
| product_id | name | category | sizes |
|------------|--------|----------|-------|
| 3 | shoes2 | shoes | 9,10 |
| 4 | shoes3 | shoes | 10,11 |
3.
| product_id | name | category |
|------------|--------|----------|
| 3 | shoes2 | shoes |
| 4 | shoes3 | shoes |
| product_id | size |
|------------|------|
| 3 | 9 |
| 3 | 10 |
| 4 | 10 |
| 4 | 11 |
演示: