连接表上的SQL连接具有多对多关系

时间:2015-10-28 23:43:18

标签: mysql sql join junction-table

我有三个表,其中2个是常规数据表,1个是多对多联结表。

两个数据表:

table products

product_id | product_name | product_color
-----------------------------------------
1          | Pear         | Green
2          | Apple        | Red
3          | Banana       | Yellow

table shops

shop_id    | shop_location
--------------------------
1          | Foo street
2          | Bar alley
3          | Fitz lane

我有一个包含shop_idproduct_id&#39>的联结表:

table shops_products

shop_id    | product_id
--------------------
1          | 1
1          | 2
2          | 1
2          | 2
2          | 3
3          | 2
3          | 3

我想从shop_id 3中的商店中选择数据。我从这里尝试了很多例子,包括连接,左连接,内部连接,但我只是不知道我在这里做什么出了什么问题。我的查询,但只是返回所有产品,无论他们是否在指定的商店,如下:

SELECT products.product_name, products.product_color
FROM products
LEFT OUTER JOIN shops_products
ON products.product_id = shops_products.product_id
AND shops_products.shop_id = 3
LEFT OUTER JOIN shops
ON shops_products.shop_id = shops.shop_id

预期输出如下:

product_name | product_color
----------------------------
Apple        | Red
Banana       | Yellow

这是在MySQL,感谢您的帮助,我真的很感激。

3 个答案:

答案 0 :(得分:33)

我喜欢从外面开始进入。 所以想象所有的列都只在一张表中被卡在一起,你可以写出类似的东西:

SELECT *
FROM products
WHERE shop_id = 3

然后,您只需添加连接即可使此语句成为可能。我们知道我们需要接下来添加连接表(因为它是直接连接到products表的,因为它有product_id)。所以接下来是接下来的事情:

SELECT products.*
FROM products
INNER JOIN shops_products
ON products.product_id = shops_products.product_id
WHERE shops_products.shop_id = 3

实际上你可以在这里停下来...因为shop_id已存在于连接表中。但是,假设您还希望商店在最后一列中的位置,然后添加商店表连接。

SELECT products.*, shops.shop_location
FROM products
INNER JOIN shops_products
ON products.product_id = shops_products.product_id
INNER JOIN shops
ON shops_products.shop_id = shops.shop_id
WHERE shops_products.shop_id = 3

答案 1 :(得分:1)

你可以试试这个。

SELECT products.product_name, products.product_color
FROM products
INNER JOIN shops_products
ON products.product_id = shops_products.product_id
WHERE shops_products.shop_id = 3

答案 2 :(得分:0)

newCourses[i] = std::move(tempCourses[i]);