使用最大值计算分配给用户的最多项目数

时间:2011-07-21 19:03:45

标签: php mysql

我试图在我的mysql数据库中查询5个单独的表,并显示分配给它们的项目数最多的actor。表格结构如下;

item
itemid | item | description | brand | date | time | path |

actor
actorid | name | actorthumb | bio |

brand
brandid | brandname | description | image |

movie
movieid | title | genre | year | moviethumb | synopsis|

request
requestid | userid | itemid | brandid | movieid | actorid | content | requestdate |

我假设我需要将请求,actor和items表连接在一起,使用COUNT函数计算为actor分配了多少项,然后使用GREATEST显示分配给它们的项目数最多的actor?

The query to join all the tables is 
$query = "SELECT greatest i.*, a.*, b.*, m.*, r.* FROM item AS i, actor AS a, brand AS    b, movie AS m, request AS r
    WHERE r.itemid = i.itemid 
    AND r.actorid = a.actorid
    AND r.brandid = b.brandid
    AND r.movieid = m.movieid";

请确认完成上述操作的最佳方法?

2 个答案:

答案 0 :(得分:1)

SELECT a.actorid, a.name
    FROM request r
        INNER JOIN actor a
            ON r.actorid = a.actorid
    GROUP BY a.actorid, a.name
    ORDER BY COUNT(DISTINCT r.itemid) DESC
    LIMIT 5

答案 1 :(得分:0)

The query to join all the tables is 
$query = "SELECT i.*, a.*, b.*, m.*, r.* FROM item AS i, actor AS a, brand AS    b, movie AS m, request AS r
    WHERE r.itemid = i.itemid 
    AND r.actorid = a.actorid
    AND r.brandid = b.brandid
    AND r.movieid = m.movieid
    ORDER BY count(i.*) DESC";