如何从数据库中选择它们以显示类别(table2)中 parent_id 下的所有产品(table1)?
例如,我想使用 cat.php?id=1 之类的链接显示/列出 parent_id = 1(儿童服装)下的所有产品,包括每页子类别下的所有产品
父类别 ID #1
- 产品#1 > category_id #5
- 产品#2 > category_id #10
- 产品#3 >> category_id #16
- 产品#4 >> category_id #20
父类别 ID #2
- 产品#5 > category_id #31
- 产品#6 > category_id #33
父类别 ID #3
- 产品#7 > category_id #27
- 产品#8 > category_id #29
这是我到目前为止所拥有的,但它仍然没有显示父类别 sqlfiddle中的所有产品
SELECT * FROM products
LEFT JOIN categories
ON products.category = categories.category_id
GROUP BY (SELECT parent_id
FROM categories
WHERE parent_id = 1
GROUP BY parent_id)
DB:类别
CREATE TABLE IF NOT EXISTS `categories` (
`category_id` int(10) NOT NULL AUTO_INCREMENT,
`parent_id` int(10) DEFAULT NULL,
`title` varchar(255) NOT NULL,
PRIMARY KEY (`category_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
数据库:产品
CREATE TABLE IF NOT EXISTS `products` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`product` varchar(255) DEFAULT NULL,
`description` longtext DEFAULT NULL,
`category` int(10) DEFAULT NULL,
`color` varchar(255) DEFAULT NULL,
`sizes` varchar(255) DEFAULT NULL,
`style` varchar(255) DEFAULT NULL,
`material` varchar(255) DEFAULT NULL,
`stock` varchar(255) DEFAULT NULL,
`ws_price` decimal(6,2) DEFAULT NULL,
`rt_price` decimal(6,2) DEFAULT NULL,
`sp_code` varchar(255) DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
类别的结构
- 童装
- --大男孩和女孩服装
- --------上衣和T恤
- --------裙子和裤子
- --男婴女婴
- --------连身衣/连体衣
- --------婴儿用品
- --------婴儿护理和玩具
- --服装套装--------中性
查看产品的代码(示例):
$getid = $_GET['id'];
$q = mysqli_query($con,"
SELECT products.*, categories.*
FROM products, categories
WHERE products.category = categories.category_id
GROUP BY categories.parent_id= $getid
");
while($row = mysqli_fetch_array($q, MYSQLI_ASSOC)){
$id = $row['id'];
$product = $row['product'];
$cat = $row['category'];
$c = mysqli_query($con,"SELECT title FROM categories WHERE category_id = $cat");
while($r = mysqli_fetch_array($c)){
$pcat= $r['title']; }
echo '<p>ID#'.$id.'-'.$product.' (Category#'.$cat.'-'.$pcat.')</p>';
}
mysqli_close($con);