我如何在MySQL中使用外键进行查询? [英] How can I query using a foreign key in MySQL?
本文介绍了我如何在MySQL中使用外键进行查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
users表
= ===================
id name status_id
1 Bobby 3
2 James 2
和
状态表
=============
id值
1等待
2已核准
3其他
status_id被设置为状态表中id的外键约束。我的查询看起来像这样:
$ p $ SELECT
FROM`users`
WHERE`status_id` = 2;
当我显示 $ row ['status_id']
它会输出
2
,但是我希望它显示为 Approved
,相反,最好的方法是什么
FROM用户u
内部连接状态在u.status_id = s.id
WHERE u.status_id = 2
Right now I have a small database with two tables that look something like this:
users table
====================
id name status_id
1 Bobby 3
2 James 2
and
statuses table
=============
id value
1 Waiting
2 Approved
3 Other
status_id is setup as a foreign key constraint to id from the statuses table. My query looks something like this:
SELECT *
FROM `users`
WHERE `status_id` = 2";
When I display $row['status_id']
it outputs 2
but I would like it to display as Approved
instead, what is the best way to accomplish this?
解决方案
SELECT u.*, s.*
FROM users u
inner join statuses s on u.status_id = s.id
WHERE u.status_id = 2
这篇关于我如何在MySQL中使用外键进行查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文