MySQL: Left join and column with the same name in different tables?

前端 未结 6 621
别那么骄傲
别那么骄傲 2020-12-03 22:10
SELECT * FROM `product` left join category on product.category_id = category.id

This query works fine. But the problem is, both the product table a

相关标签:
6条回答
  • 2020-12-03 22:24

    You can add aliases to the fields:

    SELECT
        a.id,
        a.name,
        a.category_id,
        b.id AS catId,
        b.name AS catName
    FROM
        product AS a
    LEFT JOIN
        category AS b ON a.category_id = b.category.id
    
    0 讨论(0)
  • 2020-12-03 22:33

    Use aliases with the AS keyword:

    SELECT p.id AS product_id, p.name AS product_name, c.id AS cat_id, c.name AS cat_name
    FROM `product` AS p
    LEFT JOIN category AS c ON p.category_id = c.id
    
    0 讨论(0)
  • 2020-12-03 22:41

    try this:

    SELECT product.id AS productid, 
           category.id AS categoryid, ...
    FROM `product` left join category 
           on product.category_id = category.id
    
    0 讨论(0)
  • 2020-12-03 22:44

    use the "AS" keyword like

    SELECT product.id AS pid, category.id AS cid ... FROM `product` left join category on product.category_id = category.id
    
    0 讨论(0)
  • 2020-12-03 22:44

    I had a similar problem working with MySQL in a Node.js project.

    I found that if you still want to use select * instead of listing out all columns and using an alias, the following works:

    SELECT *, category.id AS cId, category.name AS cName 
    FROM product LEFT JOIN category ON product.category_id = category.id
    

    In other words, just create aliases for the joined columns that have conflicting names. You don't need aliases on other columns or on the table names.

    0 讨论(0)
  • 2020-12-03 22:49
    SELECT p.*,c.* FROM product p LEFT JOIN category c on p.category_id = c.id;
    
    0 讨论(0)
提交回复
热议问题