我有一个小问题,有一个好的解决方案。我需要搜索更好的结果。
我有3个表,规则,含义和rule_meaning。 1规则可以有1个或更多含义。
这是
的结果SELECT * FROM rule, rule_meaning, meaning WHERE rule_meaning.rule_id = rule.id AND rule_meaning.meaning_id = meaning.i
rule.id rule.name rule.id meaning_id meaning.id meaning.name
1 RADIO - Ecouter 1 1 1 ACTIVER
1 RADIO - Ecouter 1 6 6 RADIO
2 LUMIERE Allumer 2 1 1 ACTIVER
3 RADIO + volume 3 6 6 RADIO
4 RADIO - volume 4 6 6 RADIO
当我搜索ACTIVER和RADIO我想只有RADIO - Ecouter(rule.id = 1)
我试过了
WHERE meaning.name = ACTIVER AND meaning.name = RADIO但没有结果
WHERE meaning.name = ACTIVER OR meaning.name = RADIO我有几个结果。
答案 0 :(得分:2)
您想要选择具有ACTIVER和RADIO含义的规则。您可以使用聚合执行此操作:
select *
from rule
where id in
(
select rule_id
from rule_meaning
where meaning_id in (select id from meaning where name in ('ACTIVER', 'RADIO'))
group by rule_id
having count(*) = 2 -- both meanings
);
我更喜欢的另一种方法是使用EXISTS
或IN
分别查找每个值。我在这里展示它是因为它是如何处理任务的简单方法。
select *
from rule
where id in
(
select rule_id
from rule_meaning
where meaning_id = (select id from meaning where name = 'ACTIVER')
)
and id in
(
select rule_id
from rule_meaning
where meaning_id = (select id from meaning where name = 'RADIO')
);
答案 1 :(得分:0)
您可能想要使用案例陈述,例如
CASE WHEN WHERE meaning.name = ACTIVER AND meaning.name = RADIO
THEN ....
ELSE
但我认为你问的是
WHERE meaning.name = ACTIVER AND rule.name = RADIO
AND rule.id = 1