【问题标题】:join three tables and check record连接三个表并检查记录
【发布时间】:2018-12-28 03:25:01
【问题描述】:

如果用户有记录,我想连接三个表并检查另外两个表。

表格:

table1
id | username | is_active

table2
id | userid | amount

table3
id | userid | amount

我想获取并统计 'is_active' = 1 且表 2 和表 3 上没有记录的用户

我正在尝试这个:

SELECT c.id,c.is_active, 
       COUNT(c.id) AS count,
       COUNT(a.userid) AS count1,
       COUNT(b.userid) AS count2
FROM   `tbl_members` c 
       LEFT JOIN `table1` b 
              ON c.`id` = b.`userid` 
       LEFT JOIN `table2` a 
              ON b.`userid` = a.`userid` 
WHERE  c.`is_active` = 1 
GROUP BY c.id

【问题讨论】:

标签: mysql


【解决方案1】:

这个怎么样?

select count(*) as count from
(SELECT distinct c.id
FROM   `tbl_members` c 
       LEFT JOIN `table1` b 
              ON c.`id` = b.`userid` 
       LEFT JOIN `table2` a 
              ON c.id = a.`userid` 
WHERE  c.`is_active` = 1 and a.userid is null and b.userid is null) s1

这会计算具有 is_active 集且没有对应的 a.userid 或 b.userid 的唯一 c.id。

实际上,您可以省略“distinct”,假设 c.id 是 tbl_members 的主键(因此是唯一键)。这样会更简单:

select count(*) 
FROM   `tbl_members` c 
       LEFT JOIN `table1` b 
              ON c.`id` = b.`userid` 
       LEFT JOIN `table2` a 
              ON c.id = a.`userid` 
WHERE  c.`is_active` = 1 and a.userid is null and b.userid is null

【讨论】:

  • @guessguesshoo 我刚刚更正了上述每个中的第二个左连接,我认为原始版本将允许在行中有 b 但没有 a。
猜你喜欢
  • 2022-01-23
  • 1970-01-01
  • 2014-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多