SELECT deals.id,
deals.partner_id
FROM deals
LEFT JOIN deals_partners
ON ( deals.id = deals_partners.deal_id )
WHERE 1
AND ( `deals`.`partner_id` = 222
OR CASE
WHEN deals.partner_count = 1 THEN
deals_partners.partner_id = 222
end )
ORDER BY deals.id ASC
我想抓住与合作伙伴相关的交易。
他们既可以成为交易的主人,也可以是deals.partner_id = 222,或者他们可以在deals_partners中排成一行,并与交易相关联。
上面的内容对我来说很合适,但是由于我所拥有的deal_partners数量,它给了我多个相同的交易。我把它作为左连接,我不明白为什么它仍然从deals_partners中抓取行?
更新
表:交易,列: ID,标题,名称,partner_id
表 deals_partners ,列: deal_id,partner_id
我想显示合作伙伴222的优惠。要找出合作伙伴拥有的交易,他的partner_id可以在交易行中,在合作伙伴列_id中,也可以在deals_partners中有一行,其中partner_id与deal_id相关联。
答案 0 :(得分:0)
当您加入表并匹配多个记录时,您将返回多个记录。您可以使用IN子句来防止这种情况。
SELECT deals.id,
deals.partner_id
FROM deals
WHERE `deals`.`partner_id` = 22
OR id in
(SELECT deal_id
FROM deals_partners
WHERE partner_id = 222)
ORDER BY deals.id ASC
答案 1 :(得分:0)
尝试类似:(希望它有效)
SELECT deals.id,
deals.partner_id
FROM deals
LEFT JOIN deals_partners
ON deals.id = deals_partners.deal_id AND
deals_partners.partner_id = 222
WHERE `deals`.`partner_id` = 222 OR deals_partners.partner_id = 222
ORDER BY deals.id ASC
这假设deals.id = deals_partners.deal_id AND deals_partners.partner_id = 222
只有一个匹配项。否则,您需要添加GROUP BY deals.id, deals.partner_id, deals_partners.partner_id
。