简体   繁体   English

MYSQL-选择不与其他表连接的所有行

[英]MYSQL - Select all rows that don't join with other table

I have two tables, first stores the announcements and second stores the list of users that have read the announcements. 我有两个表,第一个存储公告,第二个存储已阅读公告的用户列表。 I'm trying to capture all announcements with status of read or unread. 我正在尝试捕获所有状态为已读或未读的公告。 If the second table doesnot contain a row of user_id corresponding with that announcement_id, it's unread. 如果第二个表不包含与该announcement_id相对应的user_id行,则该行未被读取。 Here's how it looks like 看起来像这样

Announcements 公告内容

id | content | announce_on
1  | foo     | 2016-11-10
2  | bar     | 2016-11-11
3  | zim     | 2016-11-12

Announcement View Count 公告查看次数

id  | user_id | announcement_id
1   | 1       | 1
2   | 1       | 2
3   | 2       | 1
4   | 2       | 3

(user 1 has read announcement 1 and 2, user 2 has read announcement 1) (用户1已阅读公告1和2,用户2已阅读公告1)

The best thing I've got so far is 到目前为止,我最好的是

SELECT
  *,
  a.id AS annId
FROM
  announcement a
LEFT JOIN
  announcement_view_count avc
ON
  avc.announcement_id = a.id
WHERE
  a.announce_on <= CURRENT_DATE AND (avc.user_id = 1 OR avc.user_id IS NULL)

The problem is that I will not get announcement 3 at all. 问题是我根本不会收到3号公告。 The avc.user_id IS NULL part is not working right. avc.user_id IS NULL部分无法正常工作。 Announcement 3 is not showing up because it has been viewed by user 2. 由于用户2已查看公告3,所以未显示。

It's hard to explain but I want to load all anouncements and have one column that could tell me if the announcement has been viewed by a particular user. 很难解释,但我想加载所有公告,并有一栏可以告诉我该公告是否已被特定用户查看。 (who's id is available). (谁的ID可用)。 Can someone give me a hint? 有人可以给我提示吗?

I've also tried NOT EXISTS and NOT IN but they return empty results. 我也尝试过NOT EXISTS和NOT IN,但是它们返回空结果。

I'm not sure I understand the problem, but maybe you can use this to create an extra column where you can store if the user has read the announcement. 我不确定我是否理解问题,但是如果用户已阅读公告,则也许可以使用它来创建一个额外的列,以在其中存储。

CASE case_value
  WHEN when_value THEN statements
  ELSE statements
END

I think I understand what you need. 我想我了解您的需求。 Lets see: you need the list of all announcements with an additional column saying if the announcement have been read by an specific user. 让我们看一下:您需要所有公告的列表,并有一个额外的列,说明该公告是否已被特定用户阅读。 In that case you need to add the filter for the user id inside the join condition and not as a global condition in the where clause. 在这种情况下,您需要在联接条件内添加用户ID的过滤器,而不是在where子句中将其添加为全局条件。 You can use something like this: 您可以使用如下形式:

SELECT
    a.*,
    (avc.announcement_id is not NULL) wasRead
FROM
    announcement a
LEFT JOIN
    announcement_view_count avc
ON
    (avc.announcement_id = a.id AND avc.user_id = 1)
WHERE
    a.announce_on <= CURRENT_DATE
GROUP BY a.id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM