从另一个表中选择*以及计数/求和

时间:2015-12-02 06:18:17

标签: mysql sql database

我正在尝试编写一个MySQL查询来选择表a中的所有行,以及来自表b的信息,同时还查询另一个表c中的计数和值的总和,用于每一行。

我会尝试更好地解决这个问题,这是我的表格的简化版本:

  

表A

+---------+----------+-----------+
| id      | name     |      bid  |
+---------+----------+-----------+
| 1       | abc      |         1 |
| 2       | def      |         1 |
| 3       | ghi      |         2 |
+--------------------------------+
  

表B

+---------+----------+
| id      | name     |
+---------+----------+
| 1       | STAN     |      
| 2       | UCLA     | 
+--------------------+
  

表C

+---------+----------+-----------+
| id      | aid      |   cnumber |
+---------+----------+-----------+
| 1       | 1        |        40 |
| 2       | 1        |        20 |
| 3       | 2        |        10 |
| 4       | 3        |        40 |
| 5       | 3        |        20 |
| 6       | 3        |        10 |
+--------------------------------+

我需要的是一个返回包含

的行的查询
  

a.id | a.name | b.id | b.name | SUM(c.cnumber)| COUNT(c.cnumber)

我不确定MySQL中是否有这样的东西。

我目前的解决方案是尝试查询A + B左连接,然后使用A + C右连接查询UNION。它没有给我我想要的结果。

感谢。

编辑: 为此问题重写的当前查询:

SELECT
 a.id,
 a.name,
 b.id,
 b.name
 "somecolumn" as dummy_column
 "somecolumn1" as dummy_column1
FROM a
LEFT OUTER JOIN b ON a.b.id = b.id
UNION
SELECT
 "somecolumn" as dummy_column
 "somecolumn1" as dummy_column1
 "somecolumn2" as dummy_column2
 "somecolumn3" as dummy_column3
COUNT(c.cnumber) AS ccount
SUM(c.cnumber) AS sum
FROM a
RIGHT OUTER JOIN c ON a.id = c.a.id; 

不幸的是,MySQL没有全部加入,这是我的临时工作,虽然我不认为它甚至是正确的想法。

我想要的输出是表A中的所有行,其中包含表B中的一些信息,以及表C中的总计输入。

EDIT2:

        SELECT
          a.id,
          a.name,
          b.id,
          SUM(c.cnumber) as totalSum,
          (SELECT count(*) FROM c as cc WHERE cc.aid = a.id) as totalCount
        FROM
          a
        LEFT JOIN b ON a.bid = b.id
        LEFT JOIN c ON c.aid = a.id;

对于未来类似的问题,解决方案:

        SELECT
          a.id AS aid,
          a.name,
          b.id,
          (SELECT SUM(c.rating) FROM c WHERE c.aid = aid) AS totalSum,
          (SELECT COUNT(c.rating) FROM c WHERE c.aid = aid) AS totalCount
        FROM
          a
        LEFT JOIN b ON a.bid = b.id;

2 个答案:

答案 0 :(得分:1)

您的查询应该是: -

SELECT
      a.id,
      a.name,
      b.id,
      (SELECT SUM(c.cnumber) FROM c as cd WHERE cd.aid = a.id) as totalSum,
      (SELECT count(*) FROM c as cc WHERE cc.aid = a.id) as totalCount
    FROM
      a
    LEFT JOIN b ON a.bid = b.id
    LEFT JOIN c ON c.aid = a.id;

它可能对你有帮助。

答案 1 :(得分:1)

我试过你的例子。

  SELECT * ,
(SELECT SUM(cnumber) FROM `table_c` WHERE `table_c`.`iaid` = `table_a`.`id`),
(SELECT COUNT(cnumber) FROM `table_c` WHERE `table_c`.`a.id` = `table_a`.`id`) 
FROM `table_a`,`table_b` WHERE `table_b`.`id` = `table_a`.`b.id` 

我得到了以下output