查询两张表并在第二张表中替换一张表中的值 [英] Query two tables and replace values from one table in the second one

查看:66
本文介绍了查询两张表并在第二张表中替换一张表中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两张这样的表:

Say I have two tables like so:

fruits
-------------
id | name   |
-------------
1  | Apple  |
2  | Orange |
3  | Pear   |
-------------

users
-------------------
id | name | fruit |
-------------------
1  | John | 3     |
2  | Bob  | 2     |
3  | Adam | 1     |
-------------------

我想查询这两个表,并在结果中获取用户 ID、他的姓名和水果名称(用户表中的水果 ID 对应于水果的 ID),如下所示:

I would like to query both of those tables and in the result get user ID, his name and a fruit name (fruit ID in users table corresponds to the ID of the fruit) like so:

--------------------
id | name | fruit  |
--------------------
1  | John | Pear   |
2  | Bob  | Orange |
3  | Adam | Apple  |
-------------------

到目前为止,我尝试通过以下查询加入这两个查询,但没有成功.

I tried joining those two with a query below with no success so far.

"SELECT * FROM users, fruits WHERE fruits.id = fruit"

提前致谢.

推荐答案

你需要像这样JOIN水果表:

SELECT u.id, u.name, f.name FROM users u JOIN fruits f ON u.fruit = f.id

查看工作示例此处

这篇关于查询两张表并在第二张表中替换一张表中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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