我有一张产品表:
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_id
60
如果它没有配对,那没问题。 像:
SELECT p.*, c.*, p.product_name AS score
FROM (`rcp_products` p)
JOIN `rcp_shipping` s ON `s`.`shop_id` = `p`.`shop_id` AND s.country_id = 60
JOIN `rcp_category` c ON `c`.`cat_id` = `p`.`cat_id`
WHERE `p`.`cat_id` = '7'
AND `p`.`product_price_eur` > 0
AND `p`.`product_mark_delete` = 0
ORDER BY `score` asc
LIMIT 10
(还有一些额外的WHERE和另一列,我认为没有影响)
现在,我已配对产品了。因此,在产品表中是这样的:
product_id | product_name | product_pair | shop_id
1 | Abc | 0 | 0
2 | Def | 1 | 3
3 | Ghi | 1 | 2
因此,产品2和3与产品1配对。
现在,我不知道如何在我上面发布的SQL中获取country_id
product_id = 1
。
也许我的数据库结构不是最好的:)但我怎样才能做得更好?
谢谢。
答案 0 :(得分:1)
总的来说,你需要在这里使用的想法是自我加入 - 这就是你如何找到产品对。之后,只是简单的WHERE条件。
核心查询(只能从特定商店找到对的查询)看起来像这样:
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
这应该满足产品在超过1家商店销售的条件,否则查询可能会变得更短/更容易。