如何从同一个表中连接两个选择查询结果的mysql

时间:2015-12-20 10:01:01

标签: mysql

我有一个名为'记录'的mysql表。这种结构: docdate,db,cr,total

和两个查询,如:

comp = comp or function( a, b ) return a < b end

我想在一个sql语句中实现的结果如下:

1. SELECT docdate, SUM(total) as ins FROM records where db='somefilter' AND 'someotherfilters' GROUP BY docdate
2. SELECT docdate, SUM(total) as outs FROM records where cr='somefilter' GROUP BY docdate

任何想法都将受到高度赞赏。 TNX

3 个答案:

答案 0 :(得分:1)

如果您不介意使用0而不是NULL,则可以在IF内放置SUM,如下所示:

SELECT
    docdate, 
    SUM(IF(db='somefilter' AND 'someotherfilters', total, 0)) as ins,
    SUM(IF(cr='somefilter', total, 0)) as outs
FROM records
GROUP BY docdate

编辑:

如果您确实想要NULL个值,可以将SUM包装在NULLIF语句中

... NULLIF(SUM(...), 0) AS ...

答案 1 :(得分:0)

我喜欢SUMIF的答案 - 这是获得相同结果的另一种方法(但是根据要求返回null)

请记住,如果记录表很大(因为两者都需要顺序扫描),这两种方法都会出现可怕的性能问题。这是SQL小提琴http://sqlfiddle.com/#!9/b066c/1

SELECT
  docdate,
  (
    SELECT SUM(total) FROM records r2 WHERE r2.docdate = records.docdate AND r2.field1 = 'Live'
  ) as ins,
  (
    SELECT SUM(total) FROM records r3 WHERE r3.docdate = records.docdate AND r3.field1 = 'Test' AND r3.field2 = 'OK'
  ) as outs
FROM
  records
GROUP BY 1

答案 2 :(得分:0)

一种方法是使用UNION,请参阅http://dev.mysql.com/doc/refman/5.7/en/union.html

SELECT docdate, SUM(ins) as ins , SUM(outs) as outs
FROM 
(
    (
    SELECT docdate, SUM(total) as ins , null as outs
    FROM records 
    where db='somefilter' AND 'someotherfilters' 
    GROUP BY docdate
    )
    UNION
    (
    SELECT docdate, null as ins, SUM(total) as outs 
    FROM records 
    where cr='somefilter' GROUP BY docdate
    )
) AS t
GROUP BY docdate;