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

双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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?