sql选择条件2表的总和?

时间:2017-07-04 04:24:28

标签: sql

我有2张桌子

Table Connection
----------------------------------------
|  ID       |  Member_ID  |  Connection| 
----------------------------------------
|  1        |  100        |  22        | 
----------------------------------------
|  2        |  101        |  15        | 
----------------------------------------
|  3        |  102        |  19        | 
----------------------------------------
|  4        |  103        |  21        | 

Table Member
---------------------------
|  ID         |  Status     |
---------------------------
|  100        |  0          | 
----------------------------
|  101        |  1          | 
----------------------------
|  102        |  1          | 
---------------------------
|  103        |  0          |   

我想得到Connection的总和status =1。 示例中的结果应为15+19 = 34

5 个答案:

答案 0 :(得分:1)

以下是如何使用通用SQL编写此查询的示例:

SELECT
    SUM(Connection.Connection) AS ConnectionSum
FROM
    Connection
JOIN
    Member ON Connection.Member_ID = Member.ID
WHERE
    Member.Status = 1;

答案 1 :(得分:0)

这应该适合你:

select sum(Connection) as Total_connection 
        from Connection where ID in 
( select ID from member where status = 1 );

答案 2 :(得分:0)

这是对MySQL和MariaDB数据库的引用:

SELECT SUM(Connection) 
       FROM Connection 
       WHERE Member_ID = ALL (SELECT ID FROM Member WHERE Status = 1);

OR

SELECT SUM(Connection) 
       FROM Connection 
       WHERE Member_ID IN (SELECT ID FROM Member WHERE Status = 1);

答案 3 :(得分:0)

SELECT SUM(cn。connection)sumresult FROM connection AS cn WHERE cn。member_id
IN(SELECT em.id FROM member AS em WHERE em。status = 1);

我希望它可以根据您的要求为您提供帮助

答案 4 :(得分:0)

您收到错误,因为子查询返回多个ID(多个记录),而相等的运算符只能获取一个值。使用 IN 运算符代替Equal运算符,您的错误将被删除。

select sum(connection) from connection 
where connection.member_id IN (select id from member where status=1)