mysql从多个表中选择别名

时间:2012-04-06 19:22:42

标签: mysql sql

我想将这两个查询合并为一个大查询:

SELECT COUNT(*) AS ac, SUM(Views) AS vc FROM tableA

SELECT COUNT(*) AS mc FROM tableB

在这个话题上找不到任何东西,甚至可能吗?

3 个答案:

答案 0 :(得分:4)

您可以使用三个子查询:

SELECT 
(SELECT COUNT(*) FROM tableA) AS ac,
(SELECT SUM(Views) FROM tableA) AS vc,
(SELECT COUNT(*) FROM tableB) AS mc

这不是一个非常优雅的解决方案,但应该做你需要的。

答案 1 :(得分:1)

SELECT 'tableA' as tablename, COUNT(*) AS count, SUM(Views) AS sum FROM tableA
UNION
SELECT 'tableB' as tablename, COUNT(*) AS count, 0 AS sum FROM tableB

答案 2 :(得分:0)

您可以创建一个返回SELECT COUNT(*) AS mc FROM tableB的函数,并在表A中使用它

  CREATE FUNCTION Func1() RETURNS INTEGER
  BEGIN
     DECLARE Temp INTEGER;
     SELECT COUNT(*) INTO Temp FROM tableB;
     RETURN IFNULL(Temp, 0);
  END;

  SELECT COUNT(*) AS ac, SUM(Views) AS vc, Func1() as mc FROM tableA