php 如何在 MySQL 中使用外键进行查询?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12483109/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 03:38:41  来源:igfitidea点击:

How can I query using a foreign key in MySQL?

phpmysqlforeign-keysmysqli

提问by Josh Mountain

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:

status_id 被设置为来自 statuses 表的 id 的外键约束。我的查询看起来像这样:

SELECT *
FROM `users`
WHERE `status_id` = 2";

When I display $row['status_id']it outputs 2but I would like it to display as Approvedinstead, what is the best way to accomplish this?

当我显示$row['status_id']它输出2但我希望它显示Approved为时,实现此目的的最佳方法是什么?

回答by Clodoaldo Neto

SELECT u.*, s.*
FROM users u
    inner join statuses s on u.status_id = s.id
WHERE u.status_id = 2

回答by Iberê

What you need is this

你需要的是这个

SELECT *
FROM `users`
JOIN statuses ON statuses.id = users.status_id
WHERE `status_id` = 2";

and then you can refer to

然后你可以参考

$row['value'];

回答by Tobb

The easiest way would be through joins:

最简单的方法是通过联接:

select *
from User u join Status s on u.status_id = s.id;

(if you dont want the status-id at all, you can specify the columns that you do want in the select-clause.)

(如果您根本不需要 status-id,您可以在 select-clause 中指定您需要的列。)

回答by thatidiotguy

Your users table does not have the value of approved in it. It is in your statuses table. When you request status_id you are going to get that value back from that query. You have to do a JOIN ON status_idto make this work out I think. Or do a second query.

您的用户表中没有批准的值。它在您的状态表中。当您请求 status_id 时,您将从该查询中获取该值。JOIN ON status_id我认为你必须做一个才能完成这项工作。或者进行第二次查询。

回答by CodeTalk

You aren't JOINing here:

你不是在这里加入

SELECT *
FROM Users U, Statuses S
WHERE S.id=U.status_ID
AND status_id = 2;