我有一个表(称为暂存),其中包含以下相关字段:
id (PRIMARY)
bundle_id (INT)
product (enum H,L,D)
bundle_code (enum 10,20)
我需要搜索一个bundle_id,其中bundle_code是10,然后还检索具有相同bundle_id的任何其他记录,其中product = H,并且最多两个附加记录具有相同的bundle_id,其中product!= H.我正在尝试在一个查询中执行此操作,每个bundle_id返回一行;所以我有一个bundle_ids列表,每个包含附加到该bundle_id的每个产品和id。
我想出的最好的是:
SELECT e1.bundle_id AS b_id, e1.product AS prod, e1.id AS id,
e2.bundle_id AS b2_id, e2.product AS prod2, e2.id AS id2,
e3.bundle_id AS b3_id, e3.product AS prod3, e3.id AS id3,
e4.bundle_id AS b4_id, e4.product AS prod4, e4.id AS id4,
FROM `staging` AS e1
INNER JOIN `staging` AS e2 ON (e1.bundle_id = e2.bundle_id AND e1.id != e2.id)
INNER JOIN `staging` AS e3 ON (e2.bundle_id = e3.bundle_id AND e2.id != e3.id)
INNER JOIN `staging` AS e4 ON (e1.bundle_id = e4.bundle_id AND e3.id != e4.id)
WHERE e1.bundle_code = '10'
AND e2.bundle_code = '20'
AND e2.product = 'H'
AND e3.product != 'H'
AND e4.product != 'H'
如果有四个总结果,这似乎工作正常,但如果有三个结果,那么一组数据是重复的(在这种情况下,它是id 1691):
b_id prod id b2_id prod2 id2 b3_id prod3 id3 b4_id prod4 id4
208768 NULL 1691 208768 H 1692 208768 NULL 1691 208768 L 1693
如果我添加额外的WHERE子句来尝试防止这种情况,它会返回零行,所以我认为我的JOIN语法在某个地方是关闭的。有什么想法吗?
答案 0 :(得分:4)
SELECT e1.bundle_id AS b_id, e1.product AS prod, e1.id AS id,
e2.bundle_id AS b2_id, e2.product AS prod2, e2.id AS id2,
e3.bundle_id AS b3_id, e3.product AS prod3, e3.id AS id3,
e4.bundle_id AS b4_id, e4.product AS prod4, e4.id AS id4,
FROM `staging` AS e1
INNER JOIN `staging` AS e2 ON (e1.bundle_id = e2.bundle_id AND e1.id != e2.id)
LEFT JOIN `staging` AS e3 ON (e1.bundle_id = e3.bundle_id AND e2.id != e3.id AND e3.id != e1.id AND e3.product != 'H')
LEFT JOIN `staging` AS e4 ON (e1.bundle_id = e4.bundle_id AND e3.id != e4.id AND e4.id != e2.id AND e4.id != e1.id AND e4.product != 'H')
WHERE e1.bundle_code = '10'
AND e2.bundle_code = '20'
AND e2.product = 'H';