gpt4 book ai didi

php - 左连接两个表,多列

转载 作者:行者123 更新时间:2023-11-29 21:21:58 28 4
gpt4 key购买 nike

我需要左连接两个表:CardealersApplications

我想查看哪些信用卡经销商收到了哪些申请。

每个申请都会转发给三个发卡商,因此我的表结构具有以下 3 列:receiver_1receiver_2receiver_3

接收者列中的 ID 与 cardealer_id 相同。

我的这段代码仅适用于一列:

$res1 = $wpdb->get_results( " SELECT leads.*, cardealers.*
FROM leads
LEFT JOIN cardealers ON leads.receiver_1 = cardealers.cardealer_id
WHERE leads.receiver_1 = cardealers.cardealer_id
AND cardealers.cardealer_id = '". $cardealer_id ."'" );

$res2 = $wpdb->get_results( " SELECT leads.*, cardealers.*
FROM leads
LEFT JOIN cardealers ON leads.receiver_2 = cardealers.cardealer_id
WHERE leads.receiver_2 = cardealers.cardealer_id
AND cardealers.cardealer_id = '". $cardealer_id ."'" );

$res3 = $wpdb->get_results( " SELECT leads.*, cardealers.*
FROM leads
LEFT JOIN cardealers ON leads.receiver_3 = cardealers.cardealer_id
WHERE leads.receiver_3 = cardealers.cardealer_id
AND cardealers.cardealer_id = '". $cardealer_id ."'" );

正如你所看到的,我做了 3 个单独的语句,它们都有效。但我想将这些合并成一个声明。

我该怎么做?

最佳答案

只需继续添加表并为其添加别名即可。

SELECT 
leads.*, cardealers1.*, cardealers2.*, cardealers3*
FROM leads
LEFT JOIN cardealers as cardealers1
ON leads.receiver_1 = cardealers1.cardealer_id
LEFT JOIN cardealers as cardealers2
ON leads.receiver_2 = cardealers2.cardealer_id
LEFT JOIN cardealers as cardealers3
ON leads.receiver_3 = cardealers3.cardealer_id
WHERE
leads.receiver_1 = cardealers1.cardealer_id
AND leads.receiver_2 = cardealers2.cardealer_id
AND leads.receiver_3 = cardealers3.cardealer_id
AND cardealers.cardealer_id = '". $cardealer_id ."'

编辑:最好为每个卡经销商的列指定一个别名

关于php - 左连接两个表,多列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35681079/

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