MySQL查询显示结果,但我不能限制它们?

时间:2011-11-21 15:34:29

标签: php mysql sql phpmyadmin

嗨我有这样的查询

SELECT 
    videos.*, 
    categories.cat_name , 
    ( SELECT COUNT( * ) AS count FROM user_favorites WHERE user_id = 'tw415656866' AND video_id = videos.video_id )is_favorite 
FROM `videos` 
INNER JOIN categories 
    ON categories.cat_id = videos.cat_id 
WHERE 
    date <= '2011-11-21 09:12:18' 
GROUP BY videos.video_id 
ORDER BY (votesdown / votesup) ASC 
LIMIT 0, 5 

此代码正常工作并返回如下表

video_id - 视频ID
cat_name - 类别名称
cat_id - 类别ID
标题 - 视频标题
yt_id - youtubes视频ID
voteup - vote up
votedown - 投票结果 日期 - 添加日期
推文 - 0/1(1 =推文)
is_favorite - 0/1(1 =收藏)

我要做的是将其添加到WHERE子句

AND is_favorite = 1

正如您所看到的,'is_favorite'作为列添加到数据集中但我无法查询它,因为MySQL说“is_favorite”列不存在。

确切的错误是...... “'where子句'中的未知列'is_favorite'”

有什么想法吗?

非常感谢

3 个答案:

答案 0 :(得分:3)

is_favorite确实不是列,而是子查询的别名。尝试使用

HAVING is_favorite = 1

代替。有关WHEREHAVING

之间差异的说明,请参阅http://www.w3schools.com/sql/sql_having.asp

所以你的查询应该是这样的:

SELECT 
    videos.*, 
    categories.cat_name , 
    ( SELECT COUNT( * ) AS count FROM user_favorites WHERE user_id = 'tw415656866' AND video_id = videos.video_id ) AS is_favorite 
FROM `videos` 
INNER JOIN categories ON categories.cat_id = videos.cat_id 
WHERE date <= '2011-11-21 09:12:18' 
GROUP BY videos.video_id 
HAVING is_favorite = 1
ORDER BY (votesdown / votesup) ASC 
LIMIT 0, 5 

答案 1 :(得分:1)

由于处理查询的顺序,在评估WHERE子句时is_favorite别名不可用。您需要在WHERE中重复子查询。

答案 2 :(得分:0)

您的查询:

SELECT 
    videos.*, 
    categories.cat_name , 
    T.is_favorite 
FROM `videos` 
INNER JOIN categories 
    ON categories.cat_id = videos.cat_id 
Inner join 
    ( SELECT video_id, COUNT( * ) AS IsFavorite
      FROM user_favorites  
      WHERE user_id = 'tw415656866' 
      Group by video_id ) T 
        On  T.video_id = videos.video_id 
WHERE 
    date <= '2011-11-21 09:12:18' 
  And T.isFavorite =1
GROUP BY videos.video_id 
ORDER BY (votesdown / votesup) ASC 
LIMIT 0, 5