給定如下表:匹配項目動態
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'。你能提供樣本數據和期望的結果嗎? –
類別可以有子類別... –