开发者

Linking tables in mysql

I need to know how to link two tables in a php/mysql set up then rank the results?

Here is my situation.

I have a stories table:

storyid
writerid
title
story
submitdate

and a votes table

voteid
userid
storyid
vote

I store a vote up as a 1 and a vote down as a -1

I am lo开发者_如何学编程oking for a way to join these two table then rank/sort the stories by the number of votes they recieve.

I am open to any ideas about how to do so or a different possible database schema.


I prefer to keep the names of my tables singular. It's not a "Stories" table; it's a "Story" table with multiple rows.

A vote can only be attributed to a single story, so it's a one-to-many relationship between the two. I'd put the foreign key in the votes table and let it point out the story it's associated with. Change your schema if you agree: remove the voteid from the story table and make storyid in vote a foreign key to the story table.

But with that said, perhaps you can try a query like this:

select stories.storyid, sum(vote=-1) as down, sum(vote=1) as up
from stories
inner join votes on (stories.storyid = votes.storyid)
group by stories.storyid

Corrected per ypercube's comment below.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜