无法弄清楚mysql查询

时间:2011-12-26 13:08:47

标签: mysql join

我是PHP和MySQL的新手 - >我还不好。 今天我遇到了这个问题。我有一个查询加入2个表'投票'和'故事' 这是:

SELECT stories.*, SUM(votes.vote_value) as 'total_votes' 
FROM stories JOIN votes ON stories.id = votes.item_name WHERE stories.st_date >= DATE_SUB(NOW(), INTERVAL 32 DAY) 
GROUP BY stories.id 
ORDER BY total_votes ASC LIMIT 10

我需要对其进行修改,以便仅从“故事”表中选择信息,其中字段显示= 1

一个简单的查询将如下所示:

SELECT * FROM stories WHERE showing = 1

但是我不知道如何在我加入两个数据库的第一个查询中实现它。

5 个答案:

答案 0 :(得分:2)

SELECT stories.*, SUM(votes.vote_value) as 'total_votes' 
FROM stories JOIN votes ON stories.id = votes.item_name $date 
WHERE showing=1
GROUP BY stories.id 
ORDER BY total_votes ASC LIMIT 10

只需将where贴在那里。请务必按正确顺序放置。

答案 1 :(得分:2)

SELECT stories.*, SUM(votes.vote_value) as 'total_votes' 
FROM stories, votes 
WHERE stories.id = votes.item_name AND stories.showing = 1 AND stories.st_date >= DATE_SUB(NOW(), INTERVAL 32 DAY)
GROUP BY stories.id 
ORDER BY total_votes ASC LIMIT 10

答案 2 :(得分:1)

添加它没有问题,因为它是连接的基表:

SELECT stories.*, SUM(votes.vote_value) as 'total_votes' 
FROM stories JOIN votes ON stories.id = votes.item_name $date 
WHERE stories.showing = 1
GROUP BY stories.id 
ORDER BY total_votes ASC LIMIT 10

答案 3 :(得分:1)

将您的查询更改为

SELECT stories.*, SUM(votes.vote_value) as 'total_votes' FROM stories 
JOIN votes ON stories.id = votes.item_name 
WHERE stories.showing = 1 
GROUP BY stories.id 
ORDER BY total_votes ASC LIMIT 10

答案 4 :(得分:1)

使用HAVING显示= 1,它应该可以解决您的问题。