无法使用派生表

时间:2015-08-01 22:49:39

标签: mysql

SQL新手,我似乎无法弄清楚我在尝试使用派生表时做错了什么。

测试表:

Controller  
+---------+--------+------+  
| termID  | Net    | Type | 
+---------+--------+------+  
| T901    | F001   | P    |  
+---------+--------+------+  
| T902    | F001   | A    |  
+---------+--------+------+  


Privilege  
+---------+--------+  
| termID  | Net    |  
+---------+--------+  
| T903    | F001   |  
+---------+--------+ 



Terminal  
+---------+------+  
| termID  | Act  | 
+---------+------+  
| T901    | Y    |  
| T902    | Y    |  
| T903    | Y    |  
+---------+------+  

这似乎有效 - >

SELECT *
FROM (
    SELECT termid from controller where net="F001"
    UNION
    SELECT termid from privilege where net="F001"
     ) att1
JOIN terminal
ON att1.termid=terminal.termid;

给予:

+---------+--------+------+  
| termID  | termID | Act  |  
+---------+--------+------+  
| T901    | T901   | Y    |  
| T902    | T902   | Y    |  
| T903    | T903   | Y    |  
+---------+--------+------+  

这似乎有效 - >

SELECT att1.termid
FROM (
    SELECT termid from controller where net="F001"
    UNION
    SELECT termid from privilege where net="F001"
     ) att1
JOIN terminal
ON att1.termid=terminal.termid;

给予:

+---------+  
| termID  |  
+---------+  
| T901    |  
| T902    |  
| T903    |   
+---------+  

然而,这会返回:"未知栏' att1.Act'在'字段列表' - >

SELECT att1.Act
FROM (
    SELECT termid from controller where net="F001"
    UNION
    SELECT termid from privilege where net="F001"
     ) att1
JOIN terminal
ON att1.termid=terminal.termid;

由于其他人"工作"因为他们说这些专栏,我不明白为什么它不能看到这个专栏。

如何访问派生表的列?

如果有人有心情告诉我应该如何处理这个问题,我最终会尝试确定Controller或Privilege表中的所有终端是否全部处于活动状态或终端表中是否都处于活动状态。这是我的第一次尝试(但在上面的代码子集中失败了。)

SELECT COUNT(*)
FROM (
    SELECT DISTINCT att1.Act
    FROM (
        SELECT termid from controller where net="F001"
        UNION
        SELECT termid from privilege where net="F001"
         ) att1
    JOIN terminal
    ON att1.termid=terminal.termid
     ) att2;

1 个答案:

答案 0 :(得分:0)

你破碎的SQL:

SELECT att1.Act
FROM (
    SELECT termid from controller where net="F001"
    UNION
    SELECT termid from privilege where net="F001"
     ) att1
JOIN terminal
ON att1.termid=terminal.termid;
由于没有在表att1上定义列Act,因此

被破坏。

尝试使用

开始查询
SELECT att1.termId, terminal.act

并查看这是否适合您。