独特的无法连接4张桌子

时间:2018-07-21 14:28:44

标签: mysql

我试图让用户的年龄超过30天,其中is_active = 1并且在table1和table2上都没有记录

记录:

tbl_members
---------------------------
id | username | is_active |
 1 |   user1  |     1     |
---------------------------
table1
------------------------------
id | accountid | datecreated |
   |           |             |
------------------------------
table2
------------------------------
id | memberid  | datecreated |
   |           |             |
------------------------------
table3
----------------------------------------
id | memberid  |      datecreated      |
 1 |     1     | 2018-06-21 00:12:51   |
 2 |     1     | 2018-06-22 02:12:51   |
----------------------------------------

我的查询:

SELECT b.accountid, 
           a.memberid, 
           c.username,
           d.memberid AS uid,
           d.datecreated 
    FROM   `tbl_members` c 
           LEFT JOIN `table1` b 
                  ON c.`id` = b.`accountid` 
           LEFT JOIN `table2` a 
                  ON b.`accountid` = a.`memberid` 
           LEFT JOIN               
           (select distinct memberid, datecreated  from `table3` ) as  d 
                  ON c.`id` = d.`memberid`
    WHERE  c.`is_active` = 1 
           AND a.memberid IS NULL 
           AND b.accountid IS NULL 
           AND DATE_SUB(CURDATE(), INTERVAL 30 DAY) >= date(d.datecreated)
    ORDER  BY uid 

distinct无效,结果是重复的,而不是重复的,因为table3中的记录是相同的用户ID。

我得到了正确的结果,但是它是重复的,我需要在表3中区分用户

这是我的sqlfiddle

http://sqlfiddle.com/#!9/f9c3f02/1

1 个答案:

答案 0 :(得分:1)

@Amila试图告诉你的是你应该写类似的东西

SELECT b.accountid, 
       a.memberid, 
       c.username,
       d.memberid AS uid,
       d.datecreated 
FROM   `tbl_members` c 
       LEFT JOIN `table1` b 
              ON c.`id` = b.`accountid` 
       LEFT JOIN `table2` a 
              ON b.`accountid` = a.`memberid` 
       LEFT JOIN (select memberid, 
                         MIN(datecreated) datecreated -- or MAX() ...
                  from `table3` group by memberid ) as d
              ON c.`id` = d.`memberid`
WHERE  c.`is_active` = 1 
       AND a.memberid IS NULL 
       AND b.accountid IS NULL 
       AND DATE_SUB(CURDATE(), INTERVAL 30 DAY) >= date(d.datecreated)
ORDER  BY uid 

这样,表d肯定会每memberid只传送一行。根据您对表3中的第一个日期还是最后一个日期感兴趣,请在MIN()上使用MAX()datecreated。就像您很正确地注意到的那样,不是table3直接联接到您的查询,而是子查询d