2011-02-25 51 views
2

我用下面的相关领域得到了一个表(称为分期):MySQL的加入到同一个表

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的产品!= 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

基本条目是否总是为空?你也可以显示H,L,D的参赛作品。这些对每个人都是独一无二的吗? – rayman86 2011-02-25 03:18:16

+0

在bundle_code = 10的情况下,产品总是NULL,并且bundle_code = 20时总是不为NULL。每个bundle_code只能有一个H,并且每个bundle_code只能有一个H。最后一点是什么给了我麻烦。 – 2011-02-25 03:24:49

回答

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'; 
+0

它不 - 返回零结果。正如我所提到的,我尝试了几个类似的东西,它总是没有任何回报。 – 2011-02-25 03:34:25

+0

GOt it ..删除WHERE,并将它们放入JOIN中,查询上面查询中的相应表格,它应该适合您。 – amitchd 2011-02-25 03:36:28

+0

您的意思是:'INNER JOIN分段AS e2 ON(e1.bundle_id = e2.bundle_id AND e1.bundle_code ='10')'? – 2011-02-25 03:45:38