我有一个具有一对多关系的数据库(场地,相关类别),如下所示:
venue_id | venue_name
---------------------
1 | venue1
2 | venue2
和类别
venue_id | category_id
---------------------
1 | 5
2 | 7
1 | 8
2 | 5
我想要显示所有场地category_id
为5,但没有category_id
的7和8.我尝试使用这样的连接:
SELECT distinct(`venue_to_category`.`venue_id`),`venue_name`
FROM `venue_to_category` INNER JOIN `venues`
ON `venues`.venue_id = `venue_to_category`.venue_id
WHERE `category_id` != 7
AND `category_id` != 8
AND `category_id` = 5
但它没有返回正确的结果(实际上我不确定它返回的结果)
答案 0 :(得分:2)
你案件中的2件事
对于第一个,您可以使用
select
v.venue_id,
v.venue_name
from venues v
join categories c on c.venue_id = v.venue_id
where c.category_id = 5
AND NOT EXISTS
(
select 1 from categories c1 where v.venue_id = c1.venue_id
AND c1.category_id in (7,8)
);
第二个
select
v.venue_id,
v.venue_name
from venues v
join categories c on c.venue_id = v.venue_id
where c.category_id = 5
AND NOT EXISTS
(
select 1 from categories c1 where v.venue_id = c1.venue_id
AND c1.category_id in (7,8) having count(*) = 2
);
<强> DEMO 强>
答案 1 :(得分:0)
执行您网站的搜索功能时。 Match和Against比Like sql语句更好。该字段必须设置为FullText与字段上的术语匹配:
SELECT vc.venue_id, venue_name FROM venue_to_category vc, venues v WHERE MATCH(category_id) AGAINST('-7 -8 +5');
您还可以使用IN BOOLEAN MODE来允许sql语句中的运算符。例如。 ......
MATCH(category_id)反对(&#39; -7 -8 + 5&#39;在布尔模式中)......
( - )减号表示什么都不匹配&#39; -7&#39; &#39; -8&#39;
(+)这个词必须出现在比赛中。
还有许多其他运营商需要使用。有关更多操作员和说明,请参阅this page
答案 2 :(得分:-1)
尝试
SELECT distinct `venue_to_category`.`venue_id` ,`venue_name`
FROM `venue_to_category` INNER JOIN `venues`
ON `venues`.venue_id = `venue_to_category`.venue_id
WHERE `category_id` <> 7
AND `category_id` <> 8
AND `category_id` = 5
或
SELECT distinct `venue_to_category`.`venue_id` ,`venue_name`
FROM `venue_to_category` INNER JOIN `venues`
ON `venues`.venue_id = `venue_to_category`.venue_id
WHERE `category_id` NOT IN (7,8)
AND `category_id` = 5
注意:distinct
不是函数。而对于你的例子,你可以完全放弃它,因为没有重复的行。
答案 3 :(得分:-1)
SELECT v.id, v.name
FROM venues v
JOIN venue_to_category vc
ON vc.venue_id=v.id
AND vc.category_id=5
WHERE NOT EXISTS (
SELECT 1
FROM venue_to_category vci
WHERE vci.venue_id = v.id
AND vci.category_id IN (7,8)
);