在用SQL创建视图时遇到问题:
问题:从上一个问题中得到答案,并将其放在一个视图中,该视图为表示某人是作者还是编辑者的字段创建一个“类型”列名。
这是我上一个问题的输出:
SELECT 'editor', firstname, lastname
FROM editor
WHERE SUBSTRING(ssn,5,2) = '72'
UNION
SELECT 'author', firstname, lastname
FROM author
WHERE SUBSTRING(ssn,5,2) = '72';
我尝试了以下操作,但它似乎只是将所有“作者”和“编辑”行替换为“类型”。我只需要标题为“类型”
CREATE view as View1
AS
SELECT 'editor', firstname, lastname
FROM editor
WHERE SUBSTRING(ssn,5,2) = '72'
UNION
SELECT 'author', firstname, lastname
FROM author
WHERE SUBSTRING(ssn,5,2) = '72';
SELECT 'editor' as 'type', 'author' as 'type', firstname, lastname
FROM View1;
我正在寻找以下输出:
+--------+-----------+----------+
| type | firstname | lastname |
+--------+-----------+----------+
| editor | Anne | Penny |
+--------+-----------+----------+
| editor | Steve | Smith |
+--------+-----------+----------+
| author | Albert | Singer |
+--------+-----------+----------+
| author | Serge | McCluck |
+--------+-----------+----------+
| author | Robert | Blue |
+--------+-----------+----------+
答案 0 :(得分:0)
这是您要达到的目标
CREATE VIEW 'my-view' AS
SELECT 'editor' AS Type, firstname AS FName, lastname AS LName
FROM editor
WHERE SUBSTRING(ssn,5,2) = '72'
UNION
SELECT 'author' AS Type, firstname AS FName, lastname AS LName
FROM author
WHERE SUBSTRING(ssn,5,2) = '72';