帮助将此SQL查询转换为“JOIN”语法

时间:2011-09-09 01:52:09

标签: mysql sql join

我是SQL新手。有人可以帮助转换此查询,因此它使用连接语法吗?

SELECT groups.name,
       users.firstname,
       users.lastname,
       users.emailaddress,
       groupmembers.userid,
       reminders.groupid,
       reminders.ownerid,
       reminderdetails.recno,
       reminderdetails.cardid,
       reminderdetails.message
FROM   reminderdetails,
       reminders,
       groupmembers,
       users,
       groups
WHERE  assocdate = 'Y'
       AND ( reminder1 != 99
             AND ( Datediff(reminderdate, '2011-09-22') = reminder1 )
              OR ( reminder2 != 99
                   AND Datediff(reminderdate, '2011-09-22') = reminder2 ) )
       AND reminders.cardid = reminderdetails.cardid
       AND groupmembers.groupid = reminders.groupid
       AND groupmembers.sendemail = 'Y'
       AND users.recno = groupmembers.userid
       AND groups.recno = reminders.groupid

2 个答案:

答案 0 :(得分:4)

试试这个:

SELECT g.name,
       uu.firstname,
       uu.lastname,
       uu.emailaddress,
       gp.userid,
       rm.groupid,
       rm.ownerid,
       rd.recno,
       rd.cardid,
       rd.message
FROM   reminderdetails rd
JOIN   reminders rm on rm.cardid=rd.cardId
JOIN   groupmembers gp on gp.groupid=rm.groupId and gp.sendemail='Y'
JOIN   users uu on uu.recNo=gp.userId,
JOIN   groups g ON g.recno=rm.groupId
WHERE  assocdate = 'Y'
       AND ( reminder1 != 99
             AND ( Datediff(reminderdate, '2011-09-22') = reminder1 )
              OR ( reminder2 != 99
                   AND Datediff(reminderdate, '2011-09-22') = reminder2 ) )

答案 1 :(得分:1)

在不知道你的桌面结构的情况下猜测,但我认为这似乎是正确的。

编辑:刚见过另一个;我通常不喜欢用太多的子句加载JOIN,因为当你想知道什么是WHERE子句被应用时,你最终会到处搜寻。如果可能的话,我认为保持JOIN只包含JOIN并将其余部分放入WHERE更好。

我相信其他人可以过来为我射击,但那是我对它的看法:)

SELECT groups.name,
       users.firstname,
       users.lastname,
       users.emailaddress,
       groupmembers.userid,
       reminders.groupid,
       reminders.ownerid,
       reminderdetails.recno,
       reminderdetails.cardid,
       reminderdetails.message
FROM   groups
INNER JOIN groupmembers ON groups.groupid = groupmembers.groupid
INNER JOIN users ON groupmembers.userid = users.userid
INNER JOIN reminders ON users.userid = reminders.ownderid
INNER JOIN reminderdetails ON reminders.cardid = reminderdetails.cardid
WHERE  assocdate = 'Y'
       AND ( reminder1 != 99
             AND ( Datediff(reminderdate, '2011-09-22') = reminder1 )
              OR ( reminder2 != 99
                   AND Datediff(reminderdate, '2011-09-22') = reminder2 ) )
AND groupmembers.sendemail = 'Y'