我需要从表中选择所有行:Announcements
条件下,用户在表Categories_announcements
中存在行:Categories_user.category_id = Categories_announcements.category_id
我尝试了SQL查询,请参见link
它应该只返回一行Announcements.id = 1
,因为用户在Categories_user.category_id
中只有一个类别。
编辑:
我已经测试了您共享的SQL,因此这是query:
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
最佳答案
您需要将子查询与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
)
Demo