学习 MySQL 中的 LEFT JOIN

发布于 2024-09-18 04:18:25 字数 296 浏览 15 评论 0原文

亲爱的 all.i 网络编程新手,直到现在我仍然学习 MySQL 语法。 现在我开始使用LEFT JOIN方法。我知道这种方法用于在两个或多个表之间进行标准化。我在 SO 中发布了一个问题,然后收到 答案 这让我很困惑。我已经修改了该答案,但我仍然感到困惑,因为它仅对一张表使用 LEFT JOIN 。 LEFT JOIN 是否可以在一张表中使用?

dear all.i newbie at web programming and until now i still have learn about MySQL syntax.
for now i start to use LEFT JOIN method. i know that this method use for make normalization between two or many tables. I have posted a question in SO, then I receive an Answer which make me confuse. I have modified that answer,but i still confuse because it use LEFT JOIN just for one table. whether the LEFT JOIN can be used in one table?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

薯片软お妹 2024-09-25 04:18:25

您可以LEFT JOIN 一个表与其自身,就像您可以JOIN 一个表与其自身一样。您的目的通常会有所不同,因为LEFT JOIN 的具体特征是确保当右侧不存在相应行时输出中有一行;当然;您可以通过检查行的“其他部分”(通常来自右侧表的部分)的 NULL 来选择以这种方式专门选择的那些行。

例如,考虑一个表 Product,其中包含列 ID、主键、NameCategoryCost;您想要有关其类别中最便宜的产品的信息。然后...:

SELECT P1.Name, P1.Category, P1.Cost
  FROM Product AS P1
  LEFT JOIN Product AS P2
  ON (P1.Category = P2.Category and P1.Cost > P2.Cost)
  WHERE P2.ID IS NULL

是一个“表的左连接到其自身”的示例,它将回答“您想要的”规范(如果多个项目在一个类别中具有相同的最低成本,您将获得所有项目 - - 查询实际上为您提供了商品,使得其类别中没有商品更便宜,并且没有检查同等成本的商品;-)。

You can LEFT JOIN a table with itself, just like you can JOIN a table with itself. Your purpose will usually be different, because the specific characteristic of a LEFT JOIN is ensuring a row in the output when no corresponding row exists on the right, of course; you can select those rows which have specifically been selected that way by checking for NULL for the "other part" of the row, the part that would normally come from the right-side table.

Consider for example a table Product with columns ID, primary key, Name, Category, and Cost; you want info about products that are cheapest in their category. Then...:

SELECT P1.Name, P1.Category, P1.Cost
  FROM Product AS P1
  LEFT JOIN Product AS P2
  ON (P1.Category = P2.Category and P1.Cost > P2.Cost)
  WHERE P2.ID IS NULL

is an example of a "left join of a table to itself" which will answer the "you want" spec (if more than one item has the equal-lowest cost in a category you'll get them all -- the query actually gives you the items such that no item in their category is cheaper and has no checks for items of equal cost;-).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文