我需要连接两个表:Cardealers
和Applications
。
我想看看哪些经销商已收到哪些应用程序。
每个应用程序都转发给三个cardealers,因此我的表结构包含以下3列:receiver_1
,receiver_2
,receiver_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个单独的陈述,这些陈述都有效。但我想将这些结合成一个陈述。
我该怎么做?
答案 0 :(得分:0)
只需继续添加表格并将其别名。
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 ."'
编辑:如果你为每个cardealers的列提供别名,那就最好了