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 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器