doubomudichen0832 2018-01-31 19:55
浏览 681
已采纳

双LEFT JOIN与相同的表

My 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

I need to get data for two currency_id but I have an error

ambiguous column name: 'currency_id'

Is there any way to do it right or i need to use two queries?

  • 写回答

2条回答

  • doukan1258 2018-01-31 19:59
    关注

    You need to include your alias in your join, like this:

    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
    

    You may also want to do something other than select * as you will have two tables with the same columns - something like

    SELECT pair.*, company.currency_id AS company_currency_id, client.currency_id as client_currency_id, [...]
    FROM ex_pair AS pair
    [...]
    

    This way when you explicitly declare the columns you intend to use from ex_currency with an alias, you can know on the other end more easily which are client and which are company. You will need to do this for each column in the currency table that you want in your result, though that can be done if you have your table structure in your code easily enough by looping over the list of columns and appending the alias.

    $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,','); 
    

    Gives you

    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

    Add that after your SELECT pair.* and you get your columns from the currency table, aliased so you know which is which.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺