[英]How to add a row to the result of a SQL query with INNER JOIN?
In times past, when I need to add a row to the result of a SQL statement, I write a statement like this: 在过去,当我需要在SQL语句的结果中添加一行时,我写了一个这样的语句:
SELECT colA, colB FROM my_table
UNION
SELECT 'foo' AS colA, 'bar' as colB;
However, suppose I've written the following SQL: 但是,假设我编写了以下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? 当INNER JOIN到另一个这样的表时,如何将我的额外行添加到my_table?
Update : Wow, I just goofed.
更新 :哇,我只是傻逼。 It's almost going-home time.
这几乎是回家的时间。 I forgot my where clause!
我忘记了我的where子句!
SELECT t1.colA, t1.colB, t2.colC
FROM my_table t1
INNER JOIN my_other_table t2
ON t1.colB = t2.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
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 . . .
Just replace mytable
in your second query with (SELECT ...)
, the whole first query (in parenthesis): 只需用第二个查询替换
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
;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.