我想添加一个where子句以确保video_count大于零。只应返回在video_category.video_id中引用一次或多次的类别。
因为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;
感谢您的帮助。
答案 0 :(得分: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;
答案 1 :(得分: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;
不检查
答案 2 :(得分: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。*
选择*可能会影响性能。
答案 3 :(得分: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;
答案 4 :(得分: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
答案 5 :(得分: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
这应该可以解决问题