简体   繁体   English

SQL在单行中返回内部联接

[英]SQL return inner join in a single row

I have two tables: 我有两个表:

Table1:

ID | Column 1 | Column 2
1  | Value 1  | Value 2

Table 2:
ID | Column 3 | Column 4
1  | Value 4  | Value 5
1  | Value 6  | Value 7

At the moment my query is: 目前,我的查询是:

SELECT * FROM Table1 INNER JOIN Table2 ON Table1.id = Table2.id ;

returns: 收益:

id |    Column 1 |  Column 2 |  id  |   Column 3 |  Column 4
1  |    Row 1    |    Row 1  |   1  |   Row 1    |    Row 1
1  |    Row 1    |    Row 1  |   1  |   Row 2    |    Row 2
1  |    Row 1    |    Row 1  |   1  |   Row 3    |    Row 3

I want to use SQL inner join or any other join to return single row from Table1, and all other related rows from Table2 我想使用SQL内部联接或任何其他联接从Table1返回单行,并从Table2返回所有其他相关行

  id |  Column 1 |  Column 2 |  id  |   Column 3 |  Column 4
  1  |  Row 1    |    Row 1  |   1  |   Row 1    |    Row 1
                                 1  |   Row 2    |    Row 2
                                 1  |   Row 3    |    Row 3

Is that possible? 那可能吗?

This is too long for a comment. 这个评论太长了。

You can do what you want in SQL, but I discourage you from attempting it. 可以在SQL中执行所需的操作,但是我不鼓励您尝试这样做。 First, it is more cumbersome in MySQL than in other dialects (because of the lack of window functions). 首先,它比其他方言在MySQL中更麻烦(因为缺少窗口功能)。

More importantly, it violates one of the key ideas in relational databases: tables and result sets represent unordered sets. 更重要的是,它违反了关系数据库中的关键思想之一:表和结果集代表无序集。 The ordering of the rows should not matter. 行的顺序应该无关紧要。 In your result set, there is a big difference between the first row and the rest of the rows. 在结果集中,第一行与其余各行之间存在很大差异。 The meaning of many of the rows depends on what comes before it. 许多行的含义取决于之前的内容。 And, there is no "before" in unordered sets. 并且,无序集合中没有“之前”。

Although a nice challenge to get these results in SQL, it is better to do this type of formatting in the application layer. 尽管要在SQL中获得这些结果是一个艰巨的挑战,但最好在应用程序层中进行这种格式设置。 Application programming environments are more suited for adjusting results for presentation. 应用程序编程环境更适合于调整结果以进行演示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM