只获取表中存在的行?

时间:2017-02-25 15:52:43

标签: mysql sql select exists

我需要从表中选择所有行: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

5 个答案:

答案 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
        )

Demo

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

SQLFiddle

答案 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;

Demo link