MySQL:左联接和列在不同表中具有相同名称? [英] MySQL: Left join and column with the same name in different tables?

查看:77
本文介绍了MySQL:左联接和列在不同表中具有相同名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SELECT * FROM `product` left join category on product.category_id = category.id

此查询工作正常.但是问题是,产品表和类别表都具有名为名称"和"id"的字段.因此,当我获取此查询的结果时,它只给我一个名称和一个ID,但同时需要ID和名称.

This query works fine. But the problem is, both the product table and the category table have fields named "name" and "id". So when I fetch the result of this query, it gives me only one name and one id, but I want both id's and name's.

如何在不重命名字段的情况下执行此操作? 是否可以使用自定义名称(例如product_name和category_name)返回?

How can I do this without having to rename the fields? Is it possible to return with custom names such as product_name and category_name?

推荐答案

您可以将别名添加到字段:

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

这篇关于MySQL:左联接和列在不同表中具有相同名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆