开发者

How to add a row to the result of a SQL query with INNER JOIN?

开发者 https://www.devze.com 2023-02-24 02:41 出处:网络
In times past, when I need to add a row to the result of a SQL statement, I write a statement like this:

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开发者_C百科 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


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, t2.colC FROM my_table t1 INNER JOIN my_other_table t2
UNION
SELECT 'foo' as colA, 'bar' as colB, 'baz' as 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     
;
0

精彩评论

暂无评论...
验证码 换一张
取 消