仅获取 table 中存在的行?

Get only rows where exists in table?

我需要 select 来自 table 的所有行:Announcements 其中 table Categories_announcements 中存在行的用户按条件:

Categories_user.category_id = Categories_announcements.category_id

我试了SQL查询,见link

它应该 returns 我在第一行 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
        )

它 returns 我一个错误:

#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

您需要将子查询与公告相关联table:

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

你很接近。试试这个:

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 子句将其转换为内部联接。
  • Table 别名使查询更易于编写和阅读。

您的查询缺少外部查询中的 announcement table 与内部查询中的条件之间的关系:

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!
              ) 

SQLFiddle

我认为您不需要 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

没有子查询的另一种可能的解决方法:

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;

Demo link