-1

次の3つのテーブルがあります。

--users --id firstname lastname

-製品-ID名価格

--購入--user_idproduct_id

id = 1のユーザーが購入した製品を表示(選択)するにはどうすればよいですか?

4

4 に答える 4

4

以下を使用できます。

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、次のリンクが役立ちます。

SQL 結合の視覚的な説明

于 2012-09-24T20:39:33.333 に答える
1

ユーザー 1 (ユーザー名ではなく) が購入した製品のみが必要な場合は、製品と購入の間の結合で十分です。

Select prod.name, prod.price 
from products prod 
inner join purchases pur on prod.id = pur.product_id 
where pur.user_id = 1
于 2012-09-24T20:50:24.273 に答える
0

これはそれを行う必要があります:

select * from products
where id in (select product_id from purchases where user_id = 1)
于 2012-09-24T20:38:33.740 に答える
0
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
于 2012-09-24T20:39:06.260 に答える