Mysql

不能從另一個視圖中查詢一個視圖?

  • March 14, 2013

好的,我正在將數據庫從 SQL Server(我已經錯過)移動到 MySql 5.6。我在創建有效日期列表時遇到問題。在 SQL Server 中,我只是使用 CTE 來建構數字,然後是月份、年份、月份中的幾天,然後將所有內容交叉連接在一起以創建一個有效的列表。我寧願這樣做,然後創建一個巨大的表格,列出從開始到結束的所有有效日期。但是,將其轉換為一組視圖似乎不起作用:

create view `Numbers` as
   select 0 N union all select 1 union all select 2 union all
   select 3 union all select 4 union all select 5 union all
   select 6 union all select 7 union all select 8 union all select 9;
create view `Months` as
   select n.N+1 MonthNum union all select 11 union all select 12
   from `Numbers` n;

來自 MySql 的錯誤:錯誤程式碼:1109。欄位列表中的未知表“n”。

您必須按如下方式重寫第二個視圖:

create view `Months` as
   select N+1 MonthNum from `Numbers`
   union all select 11
   union all select 12
;

這裡有證據

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 4
Server version: 5.6.10-log MySQL Community Server (GPL)

Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> use test
Database changed
mysql> create view `Numbers` as
   ->     select 0 N union all select 1 union all select 2 union all
   ->     select 3 union all select 4 union all select 5 union all
   ->     select 6 union all select 7 union all select 8 union all select 9;
Query OK, 0 rows affected (0.05 sec)

mysql> create view `Months` as
   ->     select N+1 MonthNum from `Numbers`
   ->     union all select 11
   ->     union all select 12
   -> ;
Query OK, 0 rows affected (0.03 sec)

mysql>

看看查詢的輸出

mysql> select * from Months;
+----------+
| MonthNum |
+----------+
|        1 |
|        2 |
|        3 |
|        4 |
|        5 |
|        6 |
|        7 |
|        8 |
|        9 |
|       10 |
|       11 |
|       12 |
+----------+
12 rows in set (0.00 sec)

mysql>

試一試 !!!

引用自:https://dba.stackexchange.com/questions/36714