代码之家  ›  专栏  ›  技术社区  ›  Starx

如何从数据库中选择不同的列,每个列给出另一个查询结果的和(或类似的)?

  •  0
  • Starx  · 技术社区  · 14 年前

    这是查询示例

    SELECT 
        name, 
        sum(SELECT id FROM mytable WHERE cond='1' and cond2='2') as mysum1, 
        sum(SELECT id FROM mytable WHERE cond3='3' and cond4='4') as mysql2 
    FROM 
        mytable 
    WHERE 
        userid='1' and status='1';
    

    显然这不起作用,但我想你现在可以理解我的意思了。如何以这种方式检索记录。

    3 回复  |  直到 14 年前
        1
  •  0
  •   Māris Kiseļovs    14 年前

    您需要计算子查询中的和:

    SELECT 
        name, 
        (SELECT sum(numbers) FROM mytable WHERE cond='1' and cond2='2') as mysum1, 
        (SELECT sum(numbers) FROM mytable WHERE cond3='3' and cond4='4') as mysym2
    FROM 
        mytable 
    WHERE 
        userid='1' and status='1';
    
        2
  •  1
  •   Gunjan    14 年前

    试试这个

    SELECT 
        name, 
        (SELECT SUM(id) FROM mytable WHERE cond='1' and cond2='2') as mysum1, 
        (SELECT SUM(id) FROM mytable WHERE cond3='3' and cond4='4') as mysql2 
    FROM 
        mytable 
    WHERE 
        userid='1' and status='1';
    
        3
  •  0
  •   Naktibalda    14 年前

    如果要获取与这些条件匹配的行数,请使用此查询:

    SELECT 
        name, 
        SUM(cond='1' AND cond2='2') AS mysum1,
        SUM(cond3='3' AND cond4='4') AS mysum2
    FROM mytable 
    WHERE 
        userid='1' AND 
        status='1';