gpt4 book ai didi

MySQL连接到同一个表

转载 作者:行者123 更新时间:2023-11-29 01:46:43 25 4
gpt4 key购买 nike

我有一张表(称为暂存表),其中包含以下相关字段:

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 语法有问题。有什么想法吗?

最佳答案

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

关于MySQL连接到同一个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5113190/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com