如何使用 INNER JOIN 将行添加到 SQL 查询的结果中?

发布于 2024-10-31 19:31:13 字数 536 浏览 2 评论 0原文

在过去,当我需要向 SQL 语句的结果中添加一行时,我会编写如下语句:

SELECT colA, colB FROM my_table   
UNION  
SELECT 'foo' AS colA, 'bar' as colB;

但是,假设我编写了以下 SQL:

SELECT t1.colA, t1.colB, t2.colC FROM my_table t1 INNER JOIN my_other_table t2

How can I add my extra row to my_table when it is INNER像这样加入到另一张桌子吗?

更新:哇,我刚才搞砸了。快到回家的时间了。我忘记了 where 子句!

SELECT t1.colA, t1.colB, t2.colC
FROM my_table t1
INNER JOIN my_other_table t2
  ON t1.colB = t2.colC

In times past, when I need to add a row to the result of a SQL statement, I write a statement like this:

SELECT colA, colB FROM my_table   
UNION  
SELECT 'foo' AS colA, 'bar' as colB;

However, suppose I've written the following SQL:

SELECT t1.colA, t1.colB, t2.colC FROM my_table t1 INNER JOIN my_other_table t2

How can I add my extra row to my_table when it is INNER JOINed to another table like this?

Update: Wow, I just goofed. It's almost going-home time. I forgot my where clause!

SELECT t1.colA, t1.colB, t2.colC
FROM my_table t1
INNER JOIN my_other_table t2
  ON t1.colB = t2.colC

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

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

发布评论

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

评论(3

红颜悴 2024-11-07 19:31:13
SELECT 
    (t1.colA, t1.colB FROM my_table 
     UNION 
     SELECT 'foo' AS colA, 'bar' as colB) as t1 
INNER JOIN 
    my_other_table t2 ON . . .
SELECT 
    (t1.colA, t1.colB FROM my_table 
     UNION 
     SELECT 'foo' AS colA, 'bar' as colB) as t1 
INNER JOIN 
    my_other_table t2 ON . . .
寄意 2024-11-07 19:31:13
SELECT t1.colA, t1.colB, t2.colC FROM my_table t1 INNER JOIN my_other_table t2
UNION
SELECT 'foo' as colA, 'bar' as colB, 'baz' as colC
SELECT t1.colA, t1.colB, t2.colC FROM my_table t1 INNER JOIN my_other_table t2
UNION
SELECT 'foo' as colA, 'bar' as colB, 'baz' as colC
柳絮泡泡 2024-11-07 19:31:13

只需将第二个查询中的 mytable 替换为 (SELECT ...),整个第一个查询(在括号中):

SELECT t1.colA, t1.colB, t2.colC
FROM 
(   SELECT colA, colB
    FROM my_table
  UNION  
    SELECT 'foo' AS colA, 'bar' as colB
) AS t1
INNER JOIN my_other_table t2
  ON t1.colB = t2.colC     
;

Just replace mytable in your second query with (SELECT ...), the whole first query (in parenthesis):

SELECT t1.colA, t1.colB, t2.colC
FROM 
(   SELECT colA, colB
    FROM my_table
  UNION  
    SELECT 'foo' AS colA, 'bar' as colB
) AS t1
INNER JOIN my_other_table t2
  ON t1.colB = t2.colC     
;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文