将父查询列值传递到子查询中

时间:2014-05-06 06:55:38

标签: mysql sql subquery

我正在构建一个执行以获取用户奖金数据的查询。我试图通过group_concat函数将所有奖品数据放在一列中。

我几乎完成了查询,但我无法做的一件事是将父查询用户ID值传递给子查询以相应地获取数据。

+----+---------------+------------+------------------------------+
|id  |user_email     |user_name   | prizes                       |
+----+---------------+------------+------------------------------+
|1   |user_email     |user_name   | user1 prizes                 |
|2   |user_email     |user_name   | user2 prizes                 |
|3   |user_email     |user_name   | user3 prizes                 |
|4   |user_email     |user_name   | user4 prizes                 |
|5   |user_email     |user_name   | user5 prizes                 |
|6   |user_email     |user_name   | user6 prizes                 |
|7   |user_email     |user_name   | user7 prizes                 |
|8   |user_email     |user_name   | user8 prizes                 |
+----+---------------+------------+------------------------------+

以下是代码:

SELECT u.ID,u.user_email,u.user_name,
(SELECT GROUP_CONCAT( concatval ORDER BY id DESC SEPARATOR  '|~prize~|~sprt~|' )

FROM (

SELECT s.user_id,s.id, CONCAT_WS('|~value~|~sprt~|', s.id,s.offer, IFNULL(p.post_title,'N/A'), s.time, IFNULL(s.expiry_date,'N/A'), IFNULL(m.meta_value,'N/A'), IFNULL(a.meta_value,'N/A'),s.coupon) as concatval
FROM s_data s
LEFT JOIN sc_posts p ON s.campaign_id = p.ID
LEFT JOIN sc_postmeta m ON s.campaign_id = m.post_id AND m.meta_key = 'phone'
LEFT JOIN sc_postmeta a ON s.campaign_id = a.post_id AND a.meta_key = 'address'
WHERE s.user_id = 2 AND s.status = 'awarded' AND (STR_TO_DATE(s.expiry_date,'%M %d,%Y') > DATE(NOW()) OR s.expiry_date IS NULL OR s.expiry_date = '' )
ORDER BY s.id DESC LIMIT 0,7

    ) tmptable
GROUP BY user_id

) as prizes

FROM sc_users u

GROUP BY u.ID

我需要将第1行的u.id传递给第11行,它会说(WHERE s.user_id = 2)以相应地获取数据。我尝试使用它,但它在'where子句'中说“未知列'u.ID'”。有谁可以帮助我吗。提前谢谢。

1 个答案:

答案 0 :(得分:0)

您可以在FROM部分添加子查询,在用户中添加JOIN 喜欢这个

SELECT u.ID,u.user_email,u.user_name,
 prizes.concatval

FROM sc_users u 
  JOIN (SELECT GROUP_CONCAT( concatval ORDER BY id DESC SEPARATOR  '|~prize~|~sprt~|' )

FROM (

SELECT s.user_id,s.id, CONCAT_WS('|~value~|~sprt~|', s.id,s.offer, IFNULL(p.post_title,'N/A'), s.time, IFNULL(s.expiry_date,'N/A'), IFNULL(m.meta_value,'N/A'), IFNULL(a.meta_value,'N/A'),s.coupon) as concatval
FROM s_data s
LEFT JOIN sc_posts p ON s.campaign_id = p.ID
LEFT JOIN sc_postmeta m ON s.campaign_id = m.post_id AND m.meta_key = 'phone'
LEFT JOIN sc_postmeta a ON s.campaign_id = a.post_id AND a.meta_key = 'address'
WHERE s.user_id = 2 AND s.status = 'awarded' AND (STR_TO_DATE(s.expiry_date,'%M %d,%Y') > DATE(NOW()) OR s.expiry_date IS NULL OR s.expiry_date = '' )
ORDER BY s.id DESC LIMIT 0,7

    ) tmptable
GROUP BY user_id

) prizes on.prizes.user_id=u.ID

GROUP BY u.ID