在单独的表

时间:2018-05-29 23:03:04

标签: mysql sql

我正在尝试编写一个sql查询,该查询计算驻留在由UNION ALL连接在一起的不同表中的两列的行。

SELECT SUM(usernames) AS total 
   FROM 
   ((SELECT count(username) AS usernames 
        FROM table1 
        WHERE columa < '20' AND columnb = 'c' ) 
   UNION ALL 
   (SELECT count(name) AS usernames 
       FROM table2 
       WHERE columna2 < '20' and columnb2 = 'Cat' ))

当然这不起作用。我在phpMyAdmin中运行了这个语句,它给了我错误....

  

每个派生表都必须拥有自己的别名。

所以将SQL语句重写为......

SELECT SUM(usernames) AS total 
   FROM 
   ((SELECT count(username) AS usernames 
        FROM table1 a 
        WHERE a.columa < '20' AND a.columnb = 'c' ) 
   UNION ALL 
   (SELECT count(name) AS usernames 
       FROM table2 b 
       WHERE b.columna2 < '20' and b.columnb2 = 'Cat' ))

这也给了我同样的错误......

  

每个派生表都必须拥有自己的别名。

我在这里缺少什么?

3 个答案:

答案 0 :(得分:2)

select语句缺少别名,而不是table1和table2。尝试删除括号:

SELECT SUM(usernames) AS total 
   FROM 
   (SELECT count(username) AS usernames 
        FROM table1 
        WHERE columa < '20' AND columnb = 'c'  
   UNION 
   SELECT count(name) AS usernames 
       FROM table2 
       WHERE columna2 < '20' and columnb2 = 'Cat' ) a

或创建别名:

SELECT SUM(usernames) AS total 
   FROM 
   ((SELECT count(username) AS usernames 
        FROM table1 
        WHERE columa < '20' AND columnb = 'c' )  a
   UNION ALL 
   (SELECT count(name) AS usernames 
       FROM table2 
       WHERE columna2 < '20' and columnb2 = 'Cat' ) b) c

答案 1 :(得分:0)

问题不在括号中 - 这些在大多数数据库中都没问题。在最后一个之后你只需要一个别名:

SELECT SUM(usernames) AS total 
FROM ((SELECT count(username) AS usernames 
       FROM table1 a 
       WHERE a.columa < '20' AND a.columnb = 'c' 
      ) UNION ALL 
      (SELECT count(name) AS usernames 
       FROM table2 b 
       WHERE b.columna2 < '20' and b.columnb2 = 'Cat'
      )
     ) t
-------^ voila!

看起来有点令人困惑,但是union all的子查询会占用别名。对于像from子句中的表行为的子查询,需要(在MySQL中)。

答案 2 :(得分:0)

SELECT *
  FROM 
     ( SELECT 1 n) -- this a derived table, with a column alias (n)
     x -- and this is a table alias for said table