简体   繁体   中英

Can't figure out mysql query

I'm new to PHP and MySQL -> I'm not good yet. Today I came across the problem. I have a query that joins 2 tables 'votes' and 'stories' Here it is:

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

I need to modify it so it only selects information from 'stories' table where field showing = 1

A simple query would look like this:

SELECT * FROM stories WHERE showing = 1

But I have no idea how to implement it the first query where I join two databases.

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

Simply stick the where in there. Make sure to place it in the right order though.

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

Its no problem just to add it in, since it is the base table of the joins:

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

change your query to

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM