在联合所有

时间:2016-08-19 22:32:48

标签: sql

说我有以下架构:

CREATE TABLE table1(colA TEXT, colB TEXT, colC TEXT);

INSERT INTO table1(colA, colB, colC) VALUES ("A1", "B1", "C1");
INSERT INTO table1(colA, colB, colC) VALUES ("A2", "B2", "C2");

CREATE TABLE table2(colD TEXT, colE TEXT, colF TEXT);

INSERT INTO table2(colD, colE, colF) VALUES ("D1", "E1", "F1");
INSERT INTO table2(colD, colE, colF) VALUES ("D2", "E2", "F2");

然后我运行以下查询将表附加在一起以选择几列:

SELECT colA, colB FROM table1
UNION ALL
SELECT colD, colE FROM table2;

如何在union all的结果中添加另一列(比如colG)? 我想用一条消息填充这个新列的每一行 取决于该行的colA值。所以如果是细胞 内容以A开头,它应该说"这是A"或者如果它 是D然后应该说"这是D"。任何想法如何实现?非常感激。

3 个答案:

答案 0 :(得分:1)

你可以这样做:

Select 'This is an ' + ColA , * from (
SELECT colA, colB FROM table1
UNION ALL
SELECT colD, colE FROM table2) t

答案 1 :(得分:1)

有各种方法。下面显示了在联合期间检索信件。你可以在联盟之后轻松找回这封信。

MySQL不支持WITH SQL语法,这就是我加入它的原因。几乎没有任何数据库不支持,但MySQL就是其中之一。

PostgreSQL Fiddle

WITH union_tbl AS(
   SELECT colA, colB, left(colA,1) as letter FROM table1
   UNION ALL
   SELECT colD, colE, left(colD,1) as letter FROM table2
)

SELECT colA as "colA",  -- double quotes are necessary in Pg to force case
       colB as "colB", 
       'This is a' || CASE letter WHEN 'A' THEN 'n ' ELSE ' ' END || letter as "colG"
FROM union_tbl;

MySQL Fiddle

SELECT colA, 
       colB, 
       concat('This is a', case letter when 'A' then 'n ' else ' ' end, letter) as colG
FROM (
   SELECT colA, colB, left(colA,1) as letter FROM table1
   UNION ALL
   SELECT colD, colE, left(colD,1) as letter FROM table2
) union_tbl;

输出:

colA  colB  colG
A1    B1    This is an A
A2    B2    This is an A
D1    E1    This is a D
D2    E2    This is a D

答案 2 :(得分:0)

对SQL中的desirede结果使用以下查询。

SELECT CASE WHEN LEFT(CAST(ColA as VARCHAR(50)),1)='A' THEN 'This is an A'
            WHEN LEFT(CAST(ColA as VARCHAR(50)),1)='D' THEN 'This is a D' 
              ELSE 'Word in ColA is not starting with A or D' --Add if required
          END ColG , * 
FROM (
       SELECT colA, colB FROM table1
       UNION ALL
       SELECT colD, colE FROM table2) t