如果你的表格通过FK与其他2个人有关系,是否可以查询主表,同时只计算其ID中存在的ID的次数?
例如:
id title product_id contact_id
------ ------- ---------- ----------
11 Mug 110 33
11 Mug 110 297
11 Mug 378 33
11 Mug 378 297
12 Monster 299 75
12 Monster 299 291
12 Monster 299 296
我的查询结果如上:
SELECT t1.id, t1.title, t2.product_id, t3.contact_id FROM t1
JOIN t2 ON t1.id = t2.rfq_id
JOIN t3 ON t1.id = t3.rfq_id
我只对COUNT()
:
id title product_count contact_count
------ ------- ------------- -------------
11 Mug 2 2
12 Monster 1 3
答案 0 :(得分:1)
您可以尝试使用group by
和count
distinct
个值:
select t1.id
, t1.title
, count(distinct t2.product_id) as product_count
, count(distinct t3.contact_id) as contact_count
from t1
join t2 on t1.id = t2.rfq_id
join t3 on t1.id = t3.rfq_id
group by t1.id
, t1.title
答案 1 :(得分:1)
试试这些
SELECT t1.id, t1.title,
count(distinct t2.product_id) as product_id,
count(distinct t3.contact_id) as contact_id FROM t1
JOIN t2 ON t1.id = t2.rfq_id
JOIN t3 ON t1.id = t3.rfq_id
group by t1.id, t1.title
谢谢。
答案 2 :(得分:0)
您可以执行以下操作:
SELECT t1.id, t1.title,
COUNT(DISTINCT t2.product_id) AS product_count,
COUNT(DISTINCT t3.contact_id) AS contract_count
FROM t1
JOIN t2 ON t1.id = t2.rfq_id
JOIN t3 ON t1.id = t3.rfq_id
GROUP BY t1.id, t1.title