更快的方法从另一个表计数行

时间:2017-01-26 16:21:56

标签: mysql sql

还有其他方法可以更快地检索另一个表中的总记录。

这是我的示例sql代码:

SELECT *,
  (SELECT count(*) from table1 where table1.field2 = table2.field1 AND table1.status ='value1') as total1,
  (SELECT count(*) from table1 where table1.field2 = table2.field1 AND table1.status ='value2') as total2
FROM table2

3 个答案:

答案 0 :(得分:2)

在许多情况下,你的方法很好:

SELECT t2.*,
       (SELECT count(*) from table1 t1 where t1.field2 = t2.field1 AND t1.status = 'value1') as total1,
       (SELECT count(*) from table1 t1 where t1.field2 = t2.field1 AND t1.status = 'value2') as total2
FROM table2 t2;

对于性能,您需要table1(field2, status)上的索引。

另一种方法是预先汇总table1

select t2.*, t1.total1, t1.total2
from table2 t2 left join
     (select t1.field2, sum(status = 'value1') as total1, sum(status = 'value2') as total2
      from table1 t1
      group by t1.field2
     ) t1
     on t2.field1 = t1.field2;

在某些情况下,这会有更好的表现。

哪个更好用取决于数据。例如,如果table2有1行且table1有1,000,000行,其中5个匹配table2,则第一行更好。

如果table2大于table1,那么第二种方法可能会更好。

答案 1 :(得分:1)

查找子查询中每个字段的计数,然后将其与table2

连接
select t.*, a.total1, a.total2
from table2 t
left join (
    select field2, sum(status = 'value1') total1, sum(status = 'value2') total2
    from table1
    group by field2
) a on t.field1 = a.field2

答案 2 :(得分:0)

也许我误解了但是不像

那样
SELECT table1.status,
       count(*)
FROM table1 t1
JOIN table2 t2 ON t1.field2 = t2.field1
WHERE table1.status IN ('value1',
                        'value2')
GROUP BY table1.status