gpt4 book ai didi

mysql 从 3 个表中选择,其中并非所有表都包含相同行数的信息(内连接?!)

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

看来我无法理解这里和其他地方给出的一些解决方案,所以我决定问自己的问题。

我有三张 table 。像这样:

table1
id name active
123 item1 1
234 item2 0
345 item3 1 <--- not in table2!!
456 item4 1
567 item5 1

table2
id item_id instock variants deliverytimes
1 123 0 S 21days
2 123 1 M 21days
3 123 2 L 21days
4 456 1 white 10days
5 456 0 black 10days
6 234 0 yellow sold
7 456 1 green sold
8 456 0 red sold
9 567 0 big sold

table3
id item_id description
1 123 Cool Shirt
2 234 Collectors Box
3 345 Comicbook
4 456 Basecap OneSize
5 567 Cool-Mug

我尝试了从 LEFT JOIN 到 RIGHT JOIN 等多种尝试,但最终都得到了多个结果,这些结果在我需要的第一个表的 ID 中不明确,也不完整。意味着如果 table2 不包含 table1 的项目,它将不会显示在结果中。

我得到的最接近的是:

select * from table1 t1 
INNER JOIN (
SELECT * FROM table2
where (deliverytimes!='sold' OR instock>0) LIMIT 1 ) t2
ON t1.id=t2.item_id,
table3 t3
where t1.active = '1'
and t1.id = t2.item_id and t3.item_id = t1.id;

最后我需要一个列表:

“ID、名称、描述”

result (as I would like it to be)
id name description
123 item1 Cool Shirt
345 item3 Comicbook
456 item4 Basecap OneSize

确实需要满足此要求:

“项目需要是 t1.active=1” 和 “如果商品在 t2 中有行,则仅当一行等于(库存>0 或交货时间!=已售出)时才显示” 和 “如果项目在 t2 中没有行显示,只要 t1.active=1”

最后一个是问题所在。当我使用内部连接以外的其他连接时,我永远不会得到不同的 t1.id,并且使用内部连接时,我仍然会错过 t2 中不存在但仍处于事件状态的行=1。

最佳答案

开始编写查询时,请考虑要显示哪些数据。在您的情况下,您想要显示 table1 和 table3 中的数据,因此连接这些数据并从中进行选择。 table2 上的条件属于 WHERE 子句。

表2的标准是:

  • t2 中不存在任何条目
  • 或者 t2 中存在库存 > 0 或交货时间 != 已售出的条目

这意味着一个 EXISTS 子句,一个 NOT EXISTS 子句,两者都与 OR 结合。

select t1.id, t1.name, t3.description
from t1
join t3 on t3.item_id = t1.item_id
where t1.active = 1
and
(
not exists
(
select *
from t2
where t2.item_id = t1.item_id
)
or
exists
(
select *
from t2
where t2.item_id = t1.item_id
and (instock > 0 or deliverytimes != 'sold')
)
);

关于mysql 从 3 个表中选择,其中并非所有表都包含相同行数的信息(内连接?!),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33008822/

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