简体   繁体   English

如何在表决表中大多数行/投票的计数中使用JOIN和ORDER BY对MySQL搜索使用LIKE?

[英]How to use LIKE for mysql search with JOIN and ORDER BY the count of most rows/votes in the vote table?

I have three tables I need to use in a search, Movies, Reviews, and Votes. 我需要在搜索中使用三个表格:电影,评论和投票。 I want to use the LIKE function for Movie.Title and Review.Subject and order them by the amount of the most votes for each match. 我想对Movie.Title和Review.Subject使用LIKE函数,并按每次比赛的最高票数对其进行排序。

In the Votes table there is a ReviewID, UserID, IsGood. 在“投票”表中,有一个ReviewID,UserID,IsGood。 Every time a user votes, an insert is done with the MovieID, UserID, and 1 or 0 for the IsGood, 1 meaning good 0 meaning bad. 每次用户投票时,都会使用MovieID,UserID和IsGood的1或0进行插入,1表示好0表示差。

So one review may have 0 good and bad votes, or 5 good and 3 bad, etc. I would like to show the results in the following order: 因此,一个评论可能有0票赞成和反对票,或5票赞成和3票反对,等等。我想按以下顺序显示结果:

Review 1 - 10Good / 3Bad 评论1-10好/ 3坏

Review 2 - 4Good / 3Bad 评论2-4Good / 3Bad

Review 3 - 0Good / 0Bad 评论3-0良好/ 0不良

The matches with the most good votes at top, the ones with the most bad votes at the bottom. 拥有最高票数的比赛位于顶部,具有最低票数的比赛位于底部。

This is the mysql query I wrote up and is obviously wrong, but hoping someone can help me out: 这是我写的mysql查询,显然是错误的,但是希望有人可以帮帮我:

mysql_query("
    SELECT m.Title, r.Subject, v.ReviewID FROM Movies m
        LEFT JOIN Reviews r
            ON m.ID=r.MovieID
        INNER JOIN Votes v
            ON r.ID=v.ReviewID
        WHERE (m.Title LIKE '%" . $search . "%'
            OR r.Subject LIKE '%" . $search . "%')
        ORDER BY MAX(COUNT(v.IsGood='1')) LIMIT 10")or die(mysql_error());

Here is a fuller answer. 这是一个更完整的答案。 To get the sum or good votes and bad votes from a set of joined table rows, you need to group the like rows together. 要从一组联接的表行中获得总和或好票和坏票,您需要将类似的行分组在一起。

Below should give you the desired result. 下面应该给您想要的结果。

mysql_query("
    SELECT m.Title, r.Subject, v.TipID, sum(v.IsGood) as IsGood, sum(v.isBad) as isBad FROM Movies m
        LEFT JOIN Reviews r
            ON m.ID=r.MovieID
        LEFT JOIN Votes v
            ON r.ID=v.ReviewID
        WHERE (m.Title LIKE '%" . $search . "%'
            OR r.Subject LIKE '%" . $search . "%')
        GROUP BY  m.Title, r.Subject, v.TipID
        ORDER BY sum(v.IsGood) desc, sum(v.isBad) asc LIMIT 10")or die(mysql_error());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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