使用多个表获取记录数

时间:2018-12-18 22:02:54

标签: sql

嗨,我有餐桌送餐服务

delivery_id | remarks | Fid
         1    IsTicket  001
         2    NoTicket  002

还有第二张桌子

Assn | Fid 
CSCPA  001
PSCPA  002

如果我提供assn作为参数,如何基于delivery_id来计算每个Fid的{​​{1}}的计数

3 个答案:

答案 0 :(得分:1)

这应该做您想要的:

select
  t2.assn, count(*)
from deliveries d
join table2 t2 on t2.fid = d.fid
group by t2.assn

对于单个关联,您可以这样做:

select
  count(*)
from deliveries d
join table2 t2 on t2.fid = d.fid
where t2.assn = ? -- replace ? with your parameter

答案 1 :(得分:1)

您希望在两个表之间使用INNER JOIN进行合并查询,并在WHERE上进行过滤的assn子句。

SELECT d.fid, COUNT(*)
FROM deliveries d
INNER JOIN table t on t.fid = d.fid
WHERE t.assn = ?
GROUP BY d.fid

只需将?替换为您要过滤的assn

答案 2 :(得分:0)

这将起作用:

select a.delivery_id,a.Fid,b.Assn,count(delivery_id) from deliveries a,2ndtablename b
where a.Fid=b.Fid and
b.Assn=:Assn 
group by a.delivery_id,a.Fid,b.Assn;