使用子查询时出错

时间:2012-03-01 13:39:50

标签: mysql subquery

此查询不起作用:

SELECT
  user.user_id, 
  user.lastname,
  (SELECT
    reg_fee 
   FROM event 
   where event_name = (SELECT event_joined from user)
FROM user WHERE user.registration_type=1 AND user.payment_status=1

有什么问题?

2 个答案:

答案 0 :(得分:2)

你在第一个内SELECT上错过了一个右括号,但我不确定这会得到你想要的东西。

SELECT
  user.user_id, 
  user.lastname,
  (SELECT
    reg_fee 
   FROM event 
   where event_name = (SELECT event_joined from user)
  /* Close the parens and add an alias */
  ) AS reg_fee
FROM user 
WHERE user.registration_type=1 AND user.payment_status=1

假设我正确地收集了表格结构,JOIN

,可以使用user.event_joined = event.event_name更干净一点(也可能更快)
SELECT
  user.user_id,
  user.lastname,
  SUM(reg_fee)
FROM user JOIN event ON event.event_name = user.event_joined
WHERE user.registration_type = 1 AND user.payment_status = 1
GROUP BY user.user_id, user.lastname

答案 1 :(得分:0)

我建议您使用这种方式,在我看来更具可读性:

select user.user_id, user.lastname,event.req_fee
join event on (event.event_name = user.event_joined)
from user
where user.registration_type=1 AND user.payment_status=1