dongyang2229 2012-01-18 17:24
浏览 85
已采纳

如何使用LIKE进行mysql搜索,使用JOIN和ORDER BY投票表中的大多数行数/投票数?

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.

In the Votes table there is a 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.

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:

Review 1 - 10Good / 3Bad

Review 2 - 4Good / 3Bad

Review 3 - 0Good / 0Bad

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_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());
  • 写回答

1条回答 默认 最新

  • douhuang3833 2012-01-18 17:37
    关注

    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());
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题