gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 00:18:07 25 4
gpt4 key购买 nike

我正在构建一个查询来执行以获取用户奖品数据。我正在尝试通过 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

我需要将第一行的 u.id 传递到第 11 行(WHERE s.user_id = 2)以相应地获取数据。我尝试使用它,但它显示“'where 子句'中的未知列'u.ID'”。有人能帮助我吗。提前致谢。

最佳答案

您可以在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

关于mysql - 将父查询列值传递到子查询中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23487868/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com