好吧,它已经很晚了,所以这可能很明显,但我遇到了一些麻烦。
我有2张桌子。
Filter
-
id
catId
value
所有值都应该是唯一的,以便此查询获取所有值及其“id”s
select value as prodVal, id
from Filter
where catId = 7 group by prodVal
该查询返回此...
id = 82, value = 'filter1'
id = 92, value = 'filter2'
etc.. etc...
然后我需要获取“id”列表并在第二个表上处理它,即
prodFilters
-
id
filterId
productId
所以我需要计算“prodFilters”中出现的“FilterID”在前一个查询中提取的每个“ID”中出现的次数......
FOREACH(上次查询的ID)DO THIS ...
select count(*) from prodFilters
where filterId = {value from last query}
group by filterId
有没有办法通过一个查询完成所有这些,而不是运行第一个查询然后再运行多个查询?
非常感谢任何帮助。
答案 0 :(得分:3)
您应该能够使用IN
子句
SELECT filterid, COUNT(*)
FROM prodfilters
WHERE filterid IN (SELECT id
from Filter
WHERE catid = 7
group by prodVal)
GROUP BY filterid
答案 1 :(得分:2)
试试这个:
Select f.value as prodVal, f.id, Count(pf.filterId) as 'Filter Count'
From Filter f
inner join prodFilters pf on f.id = pf.filterId
where f.catId = 7
group by pf.filterId
答案 2 :(得分:1)
select Filter.value as prodVal, Filter.id , count(filterId) from prodFilters, Filter where filterId IN (select id from Filter where catId = 7) group by filterId
答案 3 :(得分:1)
select count(filterid)
from prodfilters where id in (select value as prodVal, id
from Filter
where catId = 7 group by prodVal) as temp
group by id
答案 4 :(得分:1)
SELECT catId, COUNT(*)
FROM prodFilters
WHERE catId IN (SELECT id from Filter
WHERE catId = 1 )
GROUP BY catId
答案 5 :(得分:0)
select count(p.id) , p.filderId from prodFilters as p , filter as f
where p.filterId = f.id and f.catId = 7
group by p.filterId
我认为这样可行,因为每个catId值都是唯一字段
答案 6 :(得分:0)
您可以使用
With A as {
select value as prodVal, id
from Filter
where catId = 7 group by prodVal
}
select count(*) from prodFilters
where filterId in {A.id}
group by filterId
这在oracle中运行良好,但对MySQL不确定
MySQL的:
SELECT COUNT (*)
FROM prodfilters t
JOIN
(SELECT VALUE AS prodval, ID
FROM filter
WHERE catid = 7
GROUP BY prodval) ta ON ta.ID = t.filterid
GROUP BY filterid
答案 7 :(得分:0)
您可以使用此查询
select COUNT(*) from filter as f left outer join prodFilter as p on f.Id = p.filterId