与JOIN有关的特定MySQL问题

与JOIN有关的特定MySQL问题,mysql,Mysql,我有一个产品表: product_id shop_id -> id from shop table product_pair = there is product_id, if it is paired 然后我有一张购物桌: shop_id 最后是一张发货表: shop_id -> id from shop table country_id -> id of country 我想找到可以运到country\u id60的产品 如果不是成对的,那没问题。。 比如: (还有一

我有一个产品表:

product_id
shop_id -> id from shop table
product_pair = there is product_id, if it is paired
然后我有一张购物桌:

shop_id
最后是一张发货表:

shop_id -> id from shop table
country_id -> id of country
我想找到可以运到
country\u id
60的产品

如果不是成对的,那没问题。。 比如:

(还有一些额外的WHERE's和其他专栏,我认为它们没有产生影响)

现在,我有配对产品。因此,在一个包含产品的表格中,是这样的:

product_id | product_name | product_pair | shop_id
1          | Abc          | 0            | 0
2          | Def          | 1            | 3
3          | Ghi          | 1            | 2
SELECT DISTINCT A.product_id as P1, B.product_id as P2, A.shop_id as S1, B.shop_id as S2
FROM products A, products B
WHERE (A.product_pair = B.product_id OR A.product_pair = 0) //find pair and non-paired
      AND (A.product_id > B.product_id) //ensure no duplicates (e.g. A&B and B&A)
      AND (A.shop_id = B.shop_id) //ensure that both can be found in the same shop
      AND A.shop_id = YOUR_SHOP_ID //filter to specific shop
因此,产品2和3与产品1配对。 现在,我不知道如何在我上面发布的SQL中获取
product\u id=1
country\u id

也许我的数据库结构不是最好的:)但是我怎样才能做得更好呢


谢谢。

总的来说,您需要在这里使用的想法是自连接-这就是您可以找到产品对的方式。在那之后,情况就简单了

核心查询(仅从特定商店查找配对的查询)如下所示:

product_id | product_name | product_pair | shop_id
1          | Abc          | 0            | 0
2          | Def          | 1            | 3
3          | Ghi          | 1            | 2
SELECT DISTINCT A.product_id as P1, B.product_id as P2, A.shop_id as S1, B.shop_id as S2
FROM products A, products B
WHERE (A.product_pair = B.product_id OR A.product_pair = 0) //find pair and non-paired
      AND (A.product_id > B.product_id) //ensure no duplicates (e.g. A&B and B&A)
      AND (A.shop_id = B.shop_id) //ensure that both can be found in the same shop
      AND A.shop_id = YOUR_SHOP_ID //filter to specific shop

这应该满足产品在多个商店销售时的条件,否则查询可能会变得更短/更容易

那么,最后你想找到所有可以用特定ID运送到某个国家的产品对吗?是的,我想找到所有可以或不可以用特定ID运送到该国的产品对。是的,最后我用类似的东西做到了:)谢谢!