SQL 使用 subselect 来完成 LEFT JOIN

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2466685/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 05:42:41  来源:igfitidea点击:

Using subselect to accomplish LEFT JOIN

sqlsubquerymultiple-columns

提问by Andre

Is is possible to accomplish the equivalent of a LEFT JOIN with subselect where multiple columns are required. Here's what I mean.

在需要多列的情况下,是否可以使用子选择完成等效的 LEFT JOIN。这就是我的意思。

SELECT m.*, (SELECT * FROM model WHERE id = m.id LIMIT 1) AS models FROM make m

As it stands now doing this gives me a 'Operand should contain 1 column(s)' error.

就目前而言,这样做会给我一个“操作数应该包含 1 列”错误。

Yes I know this is possible with LEFT JOIN, but I was told it was possible with subselect to I'm curious as to how it's done.

是的,我知道使用 LEFT JOIN 可以做到这一点,但有人告诉我可以使用 subselect,因为我很好奇它是如何完成的。

采纳答案by MisterZimbu

A subselect can only have one column returned from it, so you would need one subselect for each column that you would want returned from the model table.

子选择只能从中返回一列,因此您需要为要从模型表中返回的每一列进行一个子选择。

回答by mechanical_meat

There are many practical uses for what you suggest.

你的建议有很多实际用途。

This hypothetical query would return the most recent release_date(contrived example) for any make with at least one release_date, and null for any make with no release_date:

这个假设的查询将为release_date任何至少有一个的 make返回最新的(人为的例子),对于任何没有的 make返回release_datenull release_date

SELECT m.make_name, 
       sub.max_release_date
  FROM make m
       LEFT JOIN 
           (SELECT id, 
                   max(release_date) as max_release_date
              FROM make 
           GROUP BY 1) sub
       ON sub.id = m.id