次の3つのテーブルがあります。
--users --id firstname lastname
-製品-ID名価格
--購入--user_idproduct_id
id = 1のユーザーが購入した製品を表示(選択)するにはどうすればよいですか?
次の3つのテーブルがあります。
--users --id firstname lastname
-製品-ID名価格
--購入--user_idproduct_id
id = 1のユーザーが購入した製品を表示(選択)するにはどうすればよいですか?
以下を使用できます。
select u.firstname, u.lastname, p.name
from users u
inner join purchases pc
on u.id = pc.user_id
inner join products p
on pc.product_id = p.id
where u.id = 1
これにより、 のリンク テーブルを使用して 3 つのテーブルすべてが結合されますpurchases
。
構文に慣れていない場合はJOIN
、次のリンクが役立ちます。
ユーザー 1 (ユーザー名ではなく) が購入した製品のみが必要な場合は、製品と購入の間の結合で十分です。
Select prod.name, prod.price
from products prod
inner join purchases pur on prod.id = pur.product_id
where pur.user_id = 1
これはそれを行う必要があります:
select * from products
where id in (select product_id from purchases where user_id = 1)
select *
from users
join purchases
on users.id = purchases.user_id
join products
on products.id = purchases.product_id
where users.id = 1
文字通り製品のリストが必要な場合
select distinct(products.name)
from users
join purchases
on users.id = purchases.user_id
join products
on products.id = purchases.product_id
where users.id = 1
order by products.name