使用第三个连接两个表

时间:2020-01-17 13:28:09

标签: sql join union

我是SQL的新手,我正在努力使两个人使用orders表将这两个表连接起来。 订单表具有列user_id,product_id作为外键。 我试图用union做内部联接,但是我做对了。

create table users(
id int not null unique,
name varchar(25) not null,
age int not null check (age >= 18),
email varchar(50) not null unique,
password varchar(100) not null,
primary key(id, email)
);

create table products(
id int not null,
product_name varchar(25) not null,
price money not null,
stock int not null,
primary key(id)
);

create table orders(
user_id int not null,
product_id int not null,
amount int not null,
foreign key(user_id) references users(id),
foreign key(user_id) references products(id)
);

有帮助吗?

1 个答案:

答案 0 :(得分:2)

select u.name, p.product_name, o.amount
from users u
left join orders o on  u.id = o.user_id
left join products p on o.product_id = p.id;

在这小小的DEMO中,您可以看到User1订购了产品“ Apple”,并且订购了5个安宁。 User2订购了1台PC。希望对您有所帮助。

您也可以使用别名,这样最终结果看起来会更好:)

select u.name "User name"
       , p.product_name "Product"
       , o.amount "Number of products ordered"
from users u
left join orders o on  u.id = o.user_id
left join products p on o.product_id = p.id;