gpt4 book ai didi

mysql - 在 mySQL 查询中使用正确的连接

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

我有一个将多个表连接在一起的查询。

所有选定的列都不能为空,那么最好使用什么类型的连接???

这是查询:

SELECT ir.range_name, it.item_type, oi.itemQuantity, i.item_value
FROM orders o
JOIN order_items oi ON oi.orderId = o.id
JOIN items i ON i.id = oi.itemNumber
JOIN item_types it ON it.id = i.item_type
JOIN item_ranges ir ON ir.id = i.item_name
WHERE o.id = 1;

如果我已经设法得到正确答案,请告诉我!

最佳答案

您使用的语法是 INNER JOIN。这种类型的联接返回每个表中的匹配行。

这意味着您必须确保您的 orders 有一行与 order_items 匹配,然后您的 order_items 行必须匹配到 items 等。如果不是,那么您将不会返回任何行。

因此您可能必须改用 LEFT JOINLEFT JOIN 将返回 orders 表中的所有行,即使在它所连接的表中没有匹配的行也是如此。

SELECT ir.range_name, 
it.item_type,
oi.itemQuantity,
i.item_value
FROM orders o
LEFT JOIN order_items oi ON oi.orderId = o.id
LEFT JOIN items i ON i.id = oi.itemNumber
LEFT JOIN item_types it ON it.id = i.item_type
LEFT JOIN item_ranges ir ON ir.id = i.item_name
WHERE o.id = 1;

这是一个很棒的visual explanation of joins ,如果您在学习正确语法方面需要帮助。

注意:您还可以混合使用 JOIN 类型。因此,您可以在 ordersorder_items 之间使用 INNER JOIN,然后在其他一些上使用 LEFT JOIN表。这实际上取决于您的数据以及您尝试返回的结果。

关于mysql - 在 mySQL 查询中使用正确的连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15175338/

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