MySQL join to same table
I've got one table (called staging) with the following relevant fields:
id (PRIMARY)
bundle_id (INT)
product (enum H,L,D)
bundle_code (enum 10,20)
I need to search for a bundle_id where the bundle_code is 10, then also retrieve any other records with the same bundle_id where product = H and up to two additional records with the same bundle_id where product != H. I'm trying to do this all in one query, returning one row per bundle_id; so I have a list of bundle_ids, each containing every product and id attached to that bundle_id.
The best I've come up with is this:
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'
This appears to work fine if there are four total results, but if there are three results then one set of data is a duplicate (in this case, it's 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
If I add in additional WHERE clauses to try and prevent this, it returns zero rows instead, so I'm thinking my JOIN syntax is off someplace. Any ideas?
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';
精彩评论