简单的SQL多对多查询

时间:2013-12-02 12:55:20

标签: sql many-to-many

我是SQL新手,所以我想请求你的帮助:

以下是我的表格:

orders:
+----------+-------------+--------+
| order_id | customer_id | amount |
+----------+-------------+--------+
|        1 |           1 |  19.99 |
|        2 |           2 |  35.15 |
|        3 |           3 |  17.56 |
|        4 |           4 |  12.34 |
+----------+-------------+--------+
items:
+---------+-----------+------------+
| item_id | item_name | item_descr |
+---------+-----------+------------+
|       1 | item1     | its item1  |
|       2 | item2     | it's item2 |
|       3 | item3     | it`s item3 |
+---------+-----------+------------+
items_orders:
    +----------+---------+
    | order_id | item_id |
    +----------+---------+
    |        1 |       1 |
    |        1 |       2 |
    |        2 |       2 |
    |        2 |       3 |
    +----------+---------+

他们很简单,你可以看到

有人可以告诉我可以用来选择客户购买的所有商品的查询吗?

例如:

customer|item
1         1
1         2
2         2
2         3

谢谢。

2 个答案:

答案 0 :(得分:3)

尝试:

SELECT o.customer_id AS customer ,io.id AS item 
FROM orders o
INNER JOIN item_orders io ON io.order_id = o.order_id 

答案 1 :(得分:0)

SELECT * FROM orders AS O, items AS I, items_orders AS CON WHERE O.order_id = CON.order_ID AND CON.item_id = I.item_id