我的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'
有没有办法做得对,或者我需要使用两个查询?
答案 0 :(得分:1)
您需要在联接中包含别名,如下所示:
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 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.*
后添加,然后从货币表中获取列,别名,以便知道哪个是哪个。
答案 1 :(得分:0)
您可以使用您为表格提供的别名:
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