将多个MySQL查询转换为单个查询

时间:2016-11-10 10:57:02

标签: php mysql wordpress

QUERY 1 ...

$result = $wpdb->get_results("SELECT wp_users.ID,wp_users.user_login,wp_users.user_registered,wp_users.user_email,t.total,t.acc_nums FROM wp_users LEFT JOIN wp_usermeta ON ( wp_users.ID = wp_usermeta.user_id ) left join (SELECT count(*) as total,user_id,Group_concat(account_number) as acc_nums FROM `user_per_bank` group by user_id) as t on t.user_id=wp_users.ID WHERE 1=1 AND ( 
  ( 
( wp_usermeta.meta_key = 'wp_capabilities' AND wp_usermeta.meta_value LIKE '%\"editor\"%' )
  )
) ORDER BY user_registered DESC", ARRAY_A);

与QUERY结合......

$out = $wpdb->get_results('SELECT `user_id`, sum(`amount`) as outstanding FROM `assist_trans` LEFT JOIN `wp_users` ON wp_users.id = assist_trans.user_id WHERE `status` IN (0,2,4) GROUP BY assist_trans.user_id ORDER DESC');

这样可以删除“$ out”变量,我可以使用“$ result”代替......

1 个答案:

答案 0 :(得分:1)

如果我已正确理解您的问题,您需要从第一个查询到第二个查询进行连接,并在结果集中包含outstanding列。这样的事情应该有效。这是未经测试的,但如果我犯了错误,它应该指向正确的方向。

除了格式化之外,唯一的变化是结果集中的新连接和附加列。

$result = $wpdb->get_results("SELECT wp_users.ID,
                                     wp_users.user_login,
                                     wp_users.user_registered,
                                     wp_users.user_email,
                                     t.total,
                                     t.acc_nums,
                                     o.outstanding
                                FROM wp_users
                                     LEFT JOIN wp_usermeta ON ( wp_users.ID = wp_usermeta.user_id )
                                     LEFT JOIN (
                                         SELECT count(*) as total,
                                                user_id,
                                                Group_concat(account_number) as acc_nums
                                          FROM `user_per_bank`
                                       GROUP BY user_id) as t on t.user_id = wp_users.ID
                                     LEFT JOIN (
                                         SELECT `user_id`, sum(`amount`) as outstanding
                                           FROM `assist_trans`
                                                LEFT JOIN `wp_users` ON wp_users.id = assist_trans.user_id
                                          WHERE `status` IN (0,2,4)
                                       GROUP BY assist_trans.user_id) as o ON ( wp_users.ID = o.user_id )
                               WHERE 1=1
                                 AND ( 
                                       ( 
                                         ( wp_usermeta.meta_key = 'wp_capabilities' AND wp_usermeta.meta_value LIKE '%\"editor\"%' )
                                       )
                                     )
                            ORDER BY user_registered DESC",
            ARRAY_A);