我需要从表中选择所有行:Announcements
其中表Categories_announcements
中存在用于条件的用户:
Categories_user.category_id = Categories_announcements.category_id
我尝试过SQL查询,请参阅link
它应该返回我一行Announcements.id = 1
,因为用户在Categories_user.category_id
中只有一个类别。
我测试了你分享的SQL,所以这是查询:
select *
from `announcements`
where exists (
select 1
from `announcement_category`
inner join `user_category` on `user_category`.`category_id` = `announcement_category`.`category_id`
where `Auser_category`.`user_id` = 1
and `announcement_category`.`announcement_id` = announcements.id
)
它给我一个错误:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ') LIMIT 0, 25' at line 7
答案 0 :(得分:2)
我认为您不需要EXISTS子查询。基本的连接语句应该有效。
select a.*
from Categories_user cu
join Categories_announcements ca on ca.category_id = cu.category_id
join Announcements a on a.id = ca.announcement_id
where cu.user_id = 1
答案 1 :(得分:1)
您需要将子查询与Announcements表关联:
select *
from Announcements a
where exists (
select 1
from Categories_announcements ca
inner join Categories_user cu on cu.category_id = ca.category_id
where cu.user_id = 1
and ca.announcement_id = a.id
)
答案 2 :(得分:1)
你很亲密。试试这个:
select a.*
from Announcements a
where exists (select 1
from Categories_announcements ca join
Categories_user cu
on cu.category_id = ca.category_id
where ca.announcement_id = a.id and
cu.user_id = 1
);
注意:
ca.announcement_id = a.id
)的相关子句。left join
是多余的。 where
子句将其转换为内连接。答案 3 :(得分:1)
您的查询缺少外部查询中的announcement
表与内部查询中的条件之间的关系:
SELECT *
FROM announcements a
WHERE EXISTS (SELECT *
FROM categories_announcements ca
LEFT JOIN categories_user cu ON cu.category_id = ca.category_id
WHERE cu.user_id = 1 AND
a.id = ca.announcement_id -- Here!
)
答案 4 :(得分:1)
没有子查询的另一种可能的解决方法:
SELECT a.id AS accouncement_id, a.name AS annoucement_name
FROM Categories_user cu
INNER JOIN Categories_announcements ca
ON cu.category_id = ca.category_id
AND cu.user_id = 1
INNER JOIN Announcements a
ON ca.announcement_id = a.id;