我有这些表: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;");
答案 0 :(得分: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
但基于上面的yur查询,这可能也有效
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
。
希望这是有道理的
答案 1 :(得分: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
表,以便进行后续分组和聚合。