2012-01-02 62 views
1

好吧,它的晚了,所以這可能很明顯,但我遇到了一些麻煩。MySQL計數值(使用group by?)基於2個表

我有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 

所以我需要算多少「FilterID」的出現次數在「prodFilters」的存在對於在之前的查詢拉昇每一個「ID」 ......

FOREACH(ID從以前的查詢)做.. 。

select count(*) from prodFilters 
where filterId = {value from last query} 
group by filterId 

有沒有什麼辦法讓這一切都通過一個查詢來完成,而不是在運行第一查詢,然後後運行多個查詢?

任何幫助,非常感謝。

+0

不知道我理解使用'組by'沒有聚合功能的原因是什麼? AFAIK不可能這樣做 – Sathya 2012-01-02 10:04:00

+0

@Sathya:'SELECT f FROM GROUP BY f'與'SELECT DISTINCT f FROM a'相同。是的,這是可能的。 – 2012-01-02 10:09:43

+1

@ypercube雖然我知道這是可能的,但是我不知道MySQL允許'SELECT x,y從GROUP BY z'與'SELECT DISTINCT x,y from a'相同嗎?Oracle會在那裏發出錯誤 – Sathya 2012-01-02 10:15:37

回答

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,值是唯一場

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 
+0

這將返回一個170的計數,它應該是4. – 2012-01-02 10:28:29

+0

請嘗試編輯的並讓我知道。 – redmoon7777 2012-01-02 10:36:47

3

您應該能夠使用IN條款

SELECT filterid, COUNT(*) 
FROM prodfilters 
WHERE filterid IN (SELECT id 
        from Filter 
        WHERE catid = 7 
        group by prodVal) 
GROUP BY filterid 
+0

有2個表格,我只在這個查詢中看到一個表格。不,它不工作,我想要它。 – 2012-01-02 10:27:40

+0

老兄,你的編輯讓它根本不起作用 – 2012-01-02 10:33:18

+0

@BrianPatterson在兩個表上都有一些示例數據會很有幫助。無論如何現在試試。 – Sathya 2012-01-02 10:44:51

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 
+0

MySQL中沒有CTE。 – 2012-01-02 10:17:59

+0

這不適用於MySQL。不知道爲什麼它成了upvoted。 – 2012-01-02 10:27:58

+0

由於「GROUP BY prodVal」和「SELECT id」,它不適用於任何其他DBMS。 – 2012-01-02 10:34:49

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 
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 
0

您可以使用此查詢

select COUNT(*) from filter as f left outer join prodFilter as p on f.Id = p.filterId 
1
SELECT catId, COUNT(*) 
FROM prodFilters 
WHERE catId IN (SELECT id from Filter 
        WHERE catId = 1) 
GROUP BY catId 
+0

感謝您的全力幫助。最後,我根據你的一些建議,自行解決了答案。再次感謝! – 2012-01-02 10:41:55