给定如下表:匹配项目动态
CREATE TABLE catalog_categories (
cat_id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
parent_id INTEGER UNSIGNED DEFAULT NULL,
title VARCHAR(255) NOT NULL,
valid TINYINT(1) UNSIGNED NOT NULL DEFAULT 1,
PRIMARY KEY(cat_id),
FOREIGN KEY (parent_id)
REFERENCES catalog_categories(cat_id)
);
CREATE TABLE catalog_item_categories (
item_id INTEGER UNSIGNED NOT NULL,
cat_id INTEGER UNSIGNED NOT NULL,
valid TINYINT(1) UNSIGNED NOT NULL DEFAULT 1,
FOREIGN KEY (item_id)
REFERENCES catalog_items(item_id),
FOREIGN KEY (cat_id)
REFERENCES catalog_categories(cat_id)
);
而一个多维阵列作为输入,其中key => parent_id, value => cat_ids
["categories"]=>
array(2) {
[1]=>
array(2) {
[0]=>
string(1) "5"
[1]=>
string(1) "6"
}
[2]=>
array(1) {
[0]=>
string(2) "12"
}
}
我试图仅选择匹配所提供的项目类别。
SELECT a.item_id
FROM catalog_items AS a
JOIN catalog_item_categories AS b ON a.item_id = b.item_id
JOIN catalog_categories AS c ON b.cat_id = c.cat_id AND c.parent_id = 1 AND c.cat_id IN ('5', '6')
JOIN catalog_categories AS d ON b.cat_id = d.cat_id AND d.parent_id = 2 AND d.cat_id IN ('12')
WHERE a.valid = TRUE
AND b.valid = TRUE
AND c.valid = TRUE
AND d.valid = TRUE
这是我的硬编码尝试,但有没有更好的方法,或者我该如何动态构建此查询?只要我不知道有多少parent => child
会有关系。
我不明白'parent_id'。你能提供样本数据和期望的结果吗? –
类别可以有子类别... –