添加伪列以使用联接查询进行选择,以指示联接来自的表名

时间:2019-05-15 08:36:05

标签: sql postgresql

我正在使用MyBatis和PostgreSQL,需要使用mybatis鉴别器。我在testcase表上加入了10个表。我想为每个联接添加一个具有不同值的伪列,以使我知道每个联接来自哪个表。然后,我可以在MyBatis鉴别器中使用它。

我尝试了此操作,但显然不起作用,因为这会添加2列,其中每行具有pseudo_name_1pseudo_name_2

SELECT tc.testcaseid,
               tc.testname,

               a.accessoryfilterid,
               a.testcaseid,
               a.accessoryid,
               a.exclude
               'pseudo_name_1' AS pseudo_column,


               c.capabilityfilterid,
               c.exclude,
               c.testcaseid,
               c.capabilityid,
               'pseudo_name_2' AS psudo_column,

FROM testcase AS tc
    FULL JOIN accessoryfilter a on tc.testcaseid = a.testcaseid
    FULL JOIN capabilityfilter c on tc.testcaseid = a.testcaseid

我基本上想要1个伪列,其中具有accessoryfilter的行的值为pseudo_name_1,而capabilityfilter的行的值为pseudo_name_2

在postgres中有可能吗?如果可以,怎么办?

2 个答案:

答案 0 :(得分:1)

也许:


SELECT tc.testcaseid
       , tc.testname,

       , COALESCE(a.testcaseid, c.testcaseid)                   AS testcaseid   -- REDUNDANT
       , COALESCE(a.accessoryfilterid, c.capabilityfilterid)    AS filterid
       , COALESCE(a.accessoryid, c.capabilityid)                AS some_id
       , COALESCE(a.exclude, c.exclude)                         AS exclude
       , CASE         
        WHEN a.testcaseid IS NOT NULL THEN 'pseudo_name_1'
        WHEN c.testcaseid IS NOT NULL THEN 'pseudo_name_2' 
                END                                             AS pseudo_column

FROM testcase AS tc
LEFT JOIN accessoryfilter a on tc.testcaseid = a.testcaseid
LEFT JOIN capabilityfilter c on tc.testcaseid = c.testcaseid
        ;

答案 1 :(得分:1)

使用union all

SELECT tc.testcaseid, tc.testname,
       a.accessoryfilterid, a.testcaseid, a.accessoryid, a.exclude,
       'pseudo_name_1' AS pseudo_column,
FROM testcase tc JOIN
     accessoryfilter a 
     ON tc.testcaseid = a.testcaseid
UNION ALL
SELECT tc.testcaseid, tc.testname,
       c.capabilityfilterid, c.exclude, c.testcaseid, c.capabilityid,
       'pseudo_name_2' AS psudo_column
FROM testcase tc JOIN 
     capabilityfilter c 
     ON tc.testcaseid = c.testcaseid;

请注意,这也可以解决第二个JOIN条件。