MySQL如何将两个表(不同的字段)与两个语句组合在一起

时间:2019-04-10 12:13:58

标签: mysql

我想合并两个具有不同列的表。原因是我使用的报表生成器(http://wpreportbuilder.com/)仅支持一个数据库源和一个.docx模板。

第一张桌子:

CLIENT    DATE             TITLE      NAME      SOLUTION
 ABC      2019-03-01     title123   compA       fix1234
 ABC2     2019-03-01     title124   compB       fix12345

第二张表(可以有更多列):

CLIENT      DATE          CUSTOMER    REPORT       PHONE
 ABC3     2019-03-01         abc       PDF         1234

所需的输出

CLIENT        DATE      TITLE     NAME    SOLUTION   CUSTOMER   REPORT    PHONE
 ABC      2019-03-01  title123   compA   fix1234      
 ABC2     2019-03-01  title123   compB   fix12345
 ABC3     2019-03-01                                  abc        PDF     1234

这样,我可以轻松地将我的.docx模板与{title.all},{name.all}和{report.all}结合使用,并自动从数据库中导入值,并将其重新插入doc字中。

如果列数匹配,但如果列数不匹配(例如下面的代码),我可以轻松地做到这一点,它会返回“不匹配错误”。

我的代码:

SELECT 

 client AS Client,
 date as "Date Scanned",
 scanner AS Scanner,
 risk AS Risk, 
 host AS Host, 
 name AS Title, 
 solution AS Solution

FROM sss1_latest
WHERE risk regexp "High" 


UNION

SELECT 

client AS Client,
date as "Date Scanned",
Recommendation AS Solution
FROM sss2_latest
WHERE Recommendation regexp "fix1" 

上面的代码没有反映我上面的第一/第二张表。这只是出于解释目的。

1 个答案:

答案 0 :(得分:0)

UNION中的所有查询必须选择相同数量的列。您可以选择NULL''作为仅存在于另一个表中的列的占位符。

SELECT 

 client AS Client,
 date as "Date Scanned",
 scanner AS Scanner,
 risk AS Risk, 
 host AS Host, 
 name AS Title, 
 solution AS Solution,
 '' AS Customer,
 '' AS Report,
 '' AS Phone

FROM sss1_latest
WHERE risk regexp "High" 


UNION

SELECT 

 client AS Client,
 date as "Date Scanned",
 '' AS Scanner,
 '' AS Risk, 
 '' AS Host, 
 '' AS Title, 
 '' AS Solution,
 Customer,
 Report,
 Phone

FROM sss2_latest
WHERE Recommendation regexp "fix1"