mysql - 从表 B 中选择具有表 A 中的多个条件的条目

标签 mysql database

我一直在尝试使用连接、子查询连接、不存在子句来解决这个问题,但我一直无法想出一个产生正确结果的查询。

表 A - PRIMARY id(与此问题无关)

id | campaign_id | user_id
--------------------------
1         1           1
2         1           2
3         0           3
4         2           3
5         1           2

表 B - 唯一的 marketing_id+user_id

campaign_id | user_id | admin
-----------------------------
     1           1        1
     1           2        0
     1           3        0
     2           3        0

我需要做的是找到表B的实例,其中用户在表A中不再有与表B中的campaign_id相对应的条目。表A是主要内容,他们可以有表A的多个条目都出现在竞选事件中。表 B 是成员表,指示他们是营销事件的成员以及他们是否是管理员。此外,他们可能在表 B 中具有 admin 条目,但在表 A 中没有条目,因此查询必须检查 admin=0。

在示例条目中,表 B 中的无效条目为 Campaign_id 1、user_id 3

最佳答案

使用外连接,然后在 where 子句中声明外连接表的 user_id 为 null:

select    tblB.*
from      tblB
left join tblA 
       on tblA.campaign_id = tblB.campaign_id
      and tblA.user_id = tblB.user_id
where     tblB.admin = 0
      and tblA.user_id is null

关于mysql - 从表 B 中选择具有表 A 中的多个条件的条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48241636/

相关文章:

database - 如何对随时间缓慢变化的数据建模?

.net - Entity Framework 5.0 奇怪的问题

database - Access ,选择 Case ActiveControl.Name?

php - CakePhp:读取 Controller 内的查看规则消息

mysql - 无法在mamp环境中使用root@localhost连接到mysql数据库

MySQL 正则表达式搜索查询

php - 每 X 秒(异步)从数据库访问数据的最佳方式

Mysql取列中的值除以整列的平均值

MySQL 查询有任何问题吗?

android - 防止删除数据库或清除应用程序的共享首选项