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;

最佳答案

您损坏的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上未定义“行为”列。

尝试使用来开始查询

SELECT att1.termId, terminal.act


看看是否更适合您。

关于mysql - 无法使用派生表中的列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31766956/

10-13 06:46