将2个sql语句与where子句合并

时间:2013-12-30 13:37:50

标签: mysql sql left-join

我有2个表,第一个是用户(13068),另一个是邀请(211343) 用户的fbuid与邀请邀请函相同。

所以我尝试将这两个表导出为ex​​cel,看起来应该是这样的;

u.name,u.adress,u.fbuid ....,COUNT(i.id)

所以我试过了;

SELECT u.*,(SELECT COUNT(i.id) FROM invitations i WHERE i.isaccepted = 1 and i.inviter = u.fbuid) as chance FROM users WHERE u.datecreated BETWEEN '2013-01-01' AND '2014-01-01' LIMIT 0,50

SELECT *,COUNT(i.id) as chance FROM users u LEFT JOIN invitations i ON u.fbuid = i.inviter WHERE u.datecreated BETWEEN '$startdate' AND '$enddate' and i.isaccepted=1 GROUP BY fbuid

问题是左连接只为用户提供邀请,但只邀请约2000名用户,我需要列出所有这些用户。

第一个是限制50花了36秒。我无法想象有多少记录。除了加入我还能做什么?或者应该如何正确的方式。

1 个答案:

答案 0 :(得分:0)

这是left join的查询:

SELECT *, COUNT(i.id) as chance
FROM users u LEFT JOIN
     invitations i
     ON u.fbuid = i.inviter
WHERE u.datecreated BETWEEN '$startdate' AND '$enddate' and i.isaccepted=1
GROUP BY fbuid;

问题是您正在过滤i子句中的where表。由于left join,其值可能为NULL。将该条件移至on子句:

SELECT u.*, COUNT(i.id) as chance
FROM users u LEFT JOIN
     invitations i
     ON u.fbuid = i.inviter and i.isaccepted = 1
WHERE u.datecreated BETWEEN '$startdate' AND '$enddate'
GROUP BY fbuid;