2010-06-01 22 views
1

我想添加一個where子句以確保video_count大於零。應只返回video_category.video_id中一次或多次引用的類別。不能使用關聯列上的where子句

因爲video_count不是任何表中的字段,我不能這樣做。

這是查詢。

SELECT category . * , (
     SELECT COUNT(*) 
     FROM video_category 
     WHERE video_category.category_id = category.category_id 
     ) AS 'video_count' 
     FROM category 
     WHERE category.status = 1 
    AND video_count > '0' 
     AND publish_date < NOW() 
     ORDER BY updated DESC; 

感謝您的幫助。

回答

3
SELECT c.title,COUNT(vc.category_id) 
    FROM categories c 
    , video_categories vc 
WHERE c.id=vc.category_id 
    AND c.status=1 
    AND c.publish_date < NOW() 
GROUP BY c.id; 
+0

+1喜歡它應該;沒有子查詢,groupby和有;好極了! – riffnl 2010-06-01 07:45:11

+0

這可行,但沒有我需要的計數字段。 – Keyo 2010-06-04 03:19:32

+0

已更新查詢以計算每個類別的引用次數。 – Eimantas 2010-06-04 03:58:29

0

重寫一個子查詢:

SELECT * 
FROM (
    SELECT category . * , (
     SELECT COUNT(*) 
     FROM video_category 
     WHERE video_category.category_id = category.category_id 
     ) AS 'video_count' 
     FROM category 
     WHERE category.status = 1 
     AND publish_date < NOW() 
    ) dummy 
WHERE video_count > '0' 
    ORDER BY updated DESC; 
0

我不知道這是不是最好的答案,但它爲我工作。

SELECT category. * , (

SELECT COUNT(*) 
FROM video_category 
WHERE video_category.category_id = category.category_id 
) AS 'video_count' 
FROM category 
WHERE category.status =1 
AND (

SELECT COUNT(*) 
FROM video_category 
WHERE video_category.category_id = category.category_id 
) >0 
AND publish_date < NOW() 
ORDER BY updated DESC 
1

我想你可以使用GROUP BY &來實現它的HAVING子句。

SELECT category . * 
    , COUNT(v.*) as video_count 
    FROM category c 
    , video_category v 
WHERE v.category_id = c.category_id 
    AND c.status = 1 
    AND publish_date < NOW() 
GROUP BY v.category_id 
HAVING COUNT(v.*) > 0 
ORDER BY updated DESC; 

NO檢查雖然

0
select category.*, count(video_category.category_id) as c 
from category inner join video_category using(category_id) 
where category.status = 1 
and publish_date < now() 
group by video_category.category_id 
having c > 0 
order by updated desc 

這應該做的伎倆

1

這是做它的理想方式:

SELECT c.id, COUNT(vc.id) 
    FROM category as c 
    LEFT JOIN video_category as vc 
    on c.categoryid = vc.categoryid 
WHERE c.status = 1 
    AND vc.categoryid is not null 
    AND c.publish_date < NOW() 
GROUP BY c.id; 

此外,還要確保你真的需要選擇c。*

選擇*會傷害到性能。