连接三个表并检查记录

时间:2018-07-19 21:28:30

标签: mysql

我想联接三个表,并检查其他两个表(如果用户在上面有记录)。

表格:

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

1 个答案:

答案 0 :(得分:3)

怎么样?

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