计算嵌套选择结果并总结 - SQL

时间:2017-12-13 10:10:21

标签: mysql sql

第一个 SELECT 例如返回57和61.我希望第二个sql命令使用第一个 SELECT 的返回行,而不是像我在这里放置的那样(手动57)和61)。最后计算这些结果的 sum 。 (9当然是结果)

1. SELECT id FROM permissions WHERE title = 'samplezip'   
2. SELECT count(id) FROM accesslogs WHERE urlid=57 AND status='d' //result 7  
3. SELECT count(id) FROM accesslogs WHERE urlid=61 AND status='d' //result 2

2 个答案:

答案 0 :(得分:2)

我认为你可以做到这一切:

select
    count(l.id)
from
    permissions as p
    inner join accesslogs as l
        on p.id = l.urlid
where 
    p.title = 'samplezip'
    and status ='d'

答案 1 :(得分:1)

使用IN

SELECT count(*)
FROM accesslogs 
WHERE status = 'd'
  AND urlid IN (SELECT id FROM permissions WHERE title = 'samplezip');

对于每个ID的结果行加上总使用次数GROUP BY WITH ROLLUP

SELECT urlid, count(*)
FROM accesslogs 
WHERE status = 'd'
  AND urlid IN (SELECT id FROM permissions WHERE title = 'samplezip')
GROUP BY urlid WITH ROLLUP;