显示UNION中JOIN表的所有字段?

时间:2012-10-07 18:58:48

标签: mysql database

如何显示tariff_data表中已包含在UNION和JOIN中的某些字段?

例如:

SELECT  X.* FROM
    (
         SELECT phone_id, tariff_id, active  FROM table1 WHERE id = 5
      UNION
          SELECT dgt.phone_id, tns.tariff_id, dgt.active  FROM  table2 AS dgt 
                JOIN tariff_data AS tns ON tns.something = dgt.something
          WHERE id = 5
    ) as X

2 个答案:

答案 0 :(得分:1)

SELECT  X.* FROM
(
    SELECT phone_id, tariff_id, active, null as "somefield"  FROM table1 WHERE id = 5
      UNION
    SELECT dgt.phone_id, tns.tariff_id, dgt.active, tns.somefield FROM  table2 AS dgt 
            JOIN tariff_data AS tns ON tns.something = dgt.something
    WHERE id = 5
) as X

答案 1 :(得分:1)

您需要在两个Select语句中包含tariff_data中的字段,将第一个字段设置为null或者您喜欢的任何内容:

SELECT  X.* FROM
(
    SELECT phone_id, tariff_id, active, null as "somefield"  FROM table1 WHERE id = 5
      UNION
    SELECT dgt.phone_id, tns.tariff_id, dgt.active, tns.somefield FROM  table2 AS dgt 
            JOIN tariff_data AS tns ON tns.something = dgt.something
    WHERE id = 5
) as X