我有两张桌子,选项和产品。我想从选项中选择所有选项,但仅当options.id存在于任何产品列中时。这是我的两张桌子:
选项表:
id option value
1 'kategorija' 'Muški'
2 'kategorija' 'Ženski'
3 'kategorija' 'Dječji'
4 'brand' 'Casio'
5 'brand' 'Lorus'
6 'brand' 'Seiko'
7 'brand' 'Citizen'
8 'mehanizam' 'Quartz'
9 'mehanizam' 'Automatik'
10 'mehanizam' 'Eco-Drive'
11 'brojcanik' 'Analogni'
12 'brojcanik' 'Digitalni'
13 'grupa' 'Satovi'
14 'grupa' 'Naocale'
和第二个表产品:
id grupa brand mehanizam brojcanik kategorija
10380 '13' '4' '8' '11' '2'
10560 '13' '4' '9' '12' '1'
11100 '13' '6' '8' '11' '2'
12380 '14' '7' '8' '11' '2'
12490 '13' '6' '9' '11' '1'
15720 '14' '6' '9' '12' '1'
16550 '14' '5' '8' '12' '3'
我的查询尝试:
SELECT * FROM options WHERE EXISTS( SELECT 1 FROM products WHERE grupa="14" AND brand=options.id OR mehanizam=options.id OR brojcanik=options.id OR kategorija=options.id)
结果应该是:
Array
(
[0] => Array
(
[id] => 14
[option] => grupa
[value] => Naocale
)
[1] => Array
(
[id] => 7
[option] => brand
[value] => Citizen
)
[2] => Array
(
[id] => 8
[option] => mehanizam
[value] => Quartz
)
[3] => Array
(
[id] => 11
[option] => brojcanik
[value] => Analogni
)
[4] => Array
(
[id] => 2
[option] => kategorija
[value] => Zenski
)
)
这只是产品ID 12380的一行数组,这是grupa 14.数组应继续用于产品行中找到grupa 14的其他产品。 我不知道这是否仅适用于mysql查询。如果不可能,我将不得不与php进行比较,这是我试图避免的。
由于
答案 0 :(得分:3)
根据您的陈述,
我想从选项中选择所有选项,但仅当options.id存在于任何选项中时 产品列。
您可以在子查询中使用UNION ALL
合并所有值,并将结果与表options
结合使用。
SELECT DISTINCT a.*
FROM options a
INNER JOIN
(
SELECT brand col FROM products WHERE grupa = 14
UNION ALL
SELECT mehanizam col FROM products WHERE grupa = 14
UNION ALL
SELECT brojcanik col FROM products WHERE grupa = 14
UNION ALL
SELECT kategorija col FROM products WHERE grupa = 14
) b ON a.id = b.col
好多了,
SELECT *
FROM options a
WHERE EXISTS
(
SELECT 1
FROM products b
WHERE b.grupa = '14' AND
a.ID IN (brand, mehanizam, brojcanik, kategorija)
)
答案 1 :(得分:0)
您可以直接加入14
options
WHERE EXISTS (SELECT 1 FROM products JOIN options ON id = grupa ...