Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I query using a foreign key in MySQL?

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?

like image 971
Josh Mountain Avatar asked Sep 18 '12 18:09

Josh Mountain


2 Answers

SELECT u.*, s.*
FROM users u
    inner join statuses s on u.status_id = s.id
WHERE u.status_id = 2
like image 90
Clodoaldo Neto Avatar answered Sep 24 '22 15:09

Clodoaldo Neto


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'];
like image 36
Iberê Avatar answered Sep 22 '22 15:09

Iberê