[英]Double LEFT JOIN with same tables
我的SQL:
SELECT * FROM ex_pair
LEFT JOIN ex_currency as client
ON client_curr = currency_id
LEFT JOIN ex_currency as company
ON co_curr = currency_id
我需要获取两个currency_id的数据,但出现错误
列名不明确:“ currency_id”
有什么办法做对了还是我需要使用两个查询?
您需要在连接中包括别名,如下所示:
SELECT *
FROM ex_pair
LEFT JOIN ex_currency AS client
ON client_curr = client.currency_id
LEFT JOIN ex_currency as company
ON co_curr = company.currency_id
您可能还需要执行除select *之外的其他操作,因为您将有两个具有相同列的表-类似于
SELECT pair.*, company.currency_id AS company_currency_id, client.currency_id as client_currency_id, [...]
FROM ex_pair AS pair
[...]
这样,当您使用别名从ex_currency显式声明要使用的列时,您可以在另一端更轻松地知道哪些是客户端,哪些是公司。 您将需要对结果中想要的货币表中的每个列执行此操作,但是如果通过在列列表上循环并追加别名来使代码中的表结构足够容易地实现,则可以这样做。
$array = [
1=> "currency_id",
2=> "currency_name"
];
$columns = ""
foreach($array as $column){
$columns.= "company.".$column." AS company_".$column;
$columns.= ",client.".$column." AS client_".$column.",";
}
$columns = rtrim($columns,',');
给你
company.currency_id AS company_currency_id,client.currency_id AS client_currency_id,company.currency_name AS company_currency_name,client.currency_name AS client_currency_name
在SELECT pair.*
之后添加SELECT pair.*
然后从货币表中获取列,并对其进行别名化,以便知道哪个是哪个。
您可以使用赋予表的别名:
SELECT client.currency_id as client_currency, company.currency_id as company_currency
FROM ex_pair
LEFT JOIN ex_currency as client ON client_curr = client.currency_id
LEFT JOIN ex_currency as company ON co_curr = company.currency_id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.