MySQL 连接到同一个表
我有一张表(称为 staging),其中包含以下相关字段:
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_id列表,每个包含附加到该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 语法在某个地方关闭了。有什么想法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)