How to use foreign key when querying from two tables

You need SQL Join, something like this -

SELECT vehicles.car_model, users.user_name, users.user_phone
FROM vehicles
JOIN users ON vehicles.car_owner = users.users_id

I'm not sure, if you understood what foreign keys are used for. A foreign key basically says "for this entry there has to be an entry in the parent table". You said user_id is foreign key in vehicle table, which is not clear for me.

So, let's assume you have a table definition like this:

CREATE TABLE vehicles
(`id_car` int, `car_model` varchar(2), `car_owner` int);


CREATE TABLE users
(`user_id` int, `user_name` varchar(5), `user_phone` varchar(7)
, CONSTRAINT `fk_your_foreign_key` FOREIGN KEY (user_id) REFERENCES vehicles(car_owner)
);

When you want to insert a new user into the table, the user_id must be an existing entry in car_owner column in vehicles table.

Foreign keys are there to implement business rules. Does every user necessarily have to be a car owner? Or the other way round, does every car have to be owned by someone? If you can answer both questions with no, then don't implement any foreign keys for this case. But do so, if you can answer yes for sure.

To get the information you're looking for just do

SELECT 
* 
FROM 
vehicles 
INNER JOIN users ON vehicles.car_owner = users.user_id

Tags:

Mysql

Sql

Php