MYSQL将连接转换为子查询

时间:2015-11-29 05:36:34

标签: mysql join sum subquery

我尝试将连接查询转换为不具有连接并仅使用子查询,但对于我的生活,我无法找到方法。

TABLES:

TABLE1 TABLE2

使用这些表格,我尝试执行以下操作:使用子查询获取支付最多注册的与会者的FirstName,LastName和注册费用。

此查询使用连接生成该结果。

SELECT FirstName, LastName, SUM(tblregistration.RegistrationPaid) AS `AmountPaid`
FROM tblregistration, tblattendees
WHERE tblregistration.AttendeeID = tblattendees.AttendeeID
GROUP BY tblregistration.AttendeeID 
ORDER BY `AmountPaid` DESC 
LIMIT 5

Results

有办法做到这一点吗?感谢。

1 个答案:

答案 0 :(得分:2)

这应该有效:

SELECT
  (SELECT FirstName FROM tblattendees WHERE tblregistration.AttendeeID = tblattendees.AttendeeID) AS `FirstName`,
  (SELECT LastName FROM tblattendees WHERE tblregistration.AttendeeID = tblattendees.AttendeeID) AS `LastName`,
  SUM(tblregistration.RegistrationPaid) AS `AmountPaid`
FROM tblregistration
GROUP BY tblregistration.AttendeeID
ORDER BY `AmountPaid` DESC
LIMIT 5