简体   繁体   English

在mysql中创建带有联合的视图,但所有记录都显示在1列下

[英]Creating view in mysql with union all but all records are being shown under 1 column

I'm trying to create a view in MYSQL but when using Union ALL it is being shown underneath 1 column. 我正在尝试在MYSQL中创建视图,但是在使用Union ALL时,该视图显示在1列下方。 when I try to add column names it simply says that the amount of columns and results dont match 当我尝试添加列名时,它只是说列数和结果不匹配

use TestDB;
DROP VIEW if exists auditTableView;
Create view auditTableView
AS
select usernames.username from usernames LEFT JOIN auditTable on usernames.ID = auditTable.userID
Union ALL

select actionDesc.functionName from actionDesc LEFT JOIN auditTable on actionDesc.actionID = auditTable.actionID
Union all

SELECT timestamp from auditTable;


SELECT * FROM auditTableView;

From what can be gathered of your schema, it looks like you want to do an inner join from the auditTable to your usernames and actionDesc table, and select the username, actionDesc, and timestamp values from there: 从可以收集的架构中,您似乎想要从auditTable到用户名和actionDesc表进行内部联接,然后从中选择用户名,actionDesc和时间戳值:

use TestDB;
DROP VIEW if exists auditTableView;
Create view auditTableView
AS

select
    usernames.username,
    actionDesc.functionName,
    auditTable.timestamp
from auditTable
    inner join usernames
        on usernames.ID = auditTable.userID
    inner join actionDesc
        on actionDesc.actionID = auditTable.actionID;

select * from auditTableView;

With UNION , MySQL uses the column names from the first SELECT statement, and the number of columns must match. 通过UNION ,MySQL使用第一个SELECT语句中的列名,并且列数必须匹配。

You can do something like this: 您可以执行以下操作:

SELECT table1.col1, NULL AS col2 FROM table1
UNION ALL
SELECT NULL AS col1, table2.col2 FROM table2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM