1

我有这些表:users, comments, ratings, 和items

我想知道是否可以编写基本上执行此操作的 SQL 查询:

user_id 在每个表中。我想要一个 SQL 查询来计算每个表中的每次出现(users当然除外)。但是,我希望一些桌子比其他桌子承载更多的重量。然后我想计算一个“分数”。

这是一个例子:

user_id 5 出现... 2 次在项目中;5次评论;11倍的收视率。

我想要一个总计如下的公式/积分系统:

项目 2 x 5 = 10;评论 5 x 1 = 5;额定值 11 x .5 = 5.5

总计 21.5

这是我到目前为止所拥有的......

SELECT u.users
     COUNT(*) r.user_id
     COUNT(*) c.user_id
     COUNT(*) i.user_id
FROM users as u
JOIN COMMENTS as c
     ON u.user_id = c_user_id
JOIN RATINGS as r
     ON r.user_id = u.user_id
JOIN ITEMS as i
     i.user_id = u.user_id
WHERE
    ????
GROUP BY u.user_id
ORDER by total DESC

我不确定如何做数学公式部分(如果可能的话)。或者如何计算总数。

基于 John Woo 的答案的最终代码!

$sql = mysql_query("
        SELECT  u.username,
    (a.totalCount * 5) +
    (b.totalCount) +
    (c.totalCount * .2) totalScore
    FROM users u 
    LEFT JOIN
        (
            SELECT user_id, COUNT(user_id) totalCount
            FROM items 
            GROUP BY user_id
        ) a ON a.user_id= u.user_id
    LEFT JOIN
        (
            SELECT user_id, COUNT(user_id) totalCount
            FROM comments
            GROUP BY user_id
        ) b ON b.user_id= u.user_id
    LEFT JOIN
        (
            SELECT user_id, COUNT(user_id) totalCount
            FROM ratings
            GROUP BY user_id
        ) c ON c.user_id = u.user_id
    ORDER BY totalScore DESC LIMIT 10;");
4

2 回答 2

2

也许这可以帮助你,

SELECT  u.user_ID,
        (a.totalCount * 5) +
        (b.totalCount) +
        (c.totalCount * .2) totalScore
FROM    users u LEFT JOIN
            (
                SELECT user_ID, COUNT(user_ID) totalCount
                FROM items 
                GROUP BY user_ID
            ) a ON a.user_ID = u.user_ID
        LEFT JOIN
            (
                SELECT user_ID, COUNT(user_ID) totalCount
                FROM comments
                GROUP BY user_ID
            ) b ON b.user_ID = u.user_ID
        LEFT JOIN
            (
                SELECT user_ID, COUNT(user_ID) totalCount
                FROM ratings
                GROUP BY user_ID
            ) c ON c.user_ID = u.user_ID
ORDER BY totalScore DESC

但根据您上面的查询,这也可能有效

SELECT  u.users
        (COUNT(*) * .5) +
        COUNT(*) +
        (COUNT(*) * 2) totalcore
FROM users as u
        LEFT JOIN COMMENTS as c
            ON u.user_id = c_user_id
        LEFT JOIN RATINGS as r
            ON r.user_id = u.user_id
        LEFT JOIN ITEMS as i
            ON i.user_id = u.user_id
GROUP BY u.user_id
ORDER by totalcore DESC

唯一的区别是使用LEFT JOIN. 您不会INNER JOIN在这种情况下使用,因为user_id不能保证每个表上都存在机会。

希望这是有道理的

在此处输入图像描述

于 2012-09-08T01:12:04.207 回答
1

这是另一种方法:

SELECT
  u.user_id,
  SUM(s.weight) AS totalScore
FROM users u
  LEFT JOIN (
    SELECT user_id, 5.0 AS weight
    FROM items
    UNION ALL
    SELECT user_id, 1.0
    FROM comments
    UNION ALL
    SELECT user_id, 0.5
    FROM ratings
  ) s
  ON u.user_id = s.user_id
GROUP BY
  u.user_id

即,对于每个表中每个用户的每次出现,都会产生具有特定权重的行。然后将 UNIONed 权重集连接到users表中以进行后续分组和聚合。

于 2012-09-08T16:27:24.823 回答