开发者

SQL query, 3 tables

I'm in trouble and hopefully there's someone willing to help... I know the follo开发者_如何学运维wing query is not working, mostly because I'm not an expert for this stuff, but it should give you idea what my goal is. Here's my own interpretation:

SELECT ID, user_login, user_email FROM wp_users (
SELECT SUM( no_votes )
FROM wp_posts WHERE post_author = wp_users.ID 
) + (
SELECT SUM( comment_karma )
FROM wp_comments WHERE user_id = wp_users.ID )

It should output the list of all users, collect basic info from "wp_users" table and sum number of votes from two other tables ("wp_posts" and "wp_comments") where wp_users.ID match is found.


With subqueries in the Select clause:

SELECT 
  ID, 
  user_login, 
  user_email,
  (SELECT SUM( no_votes ) FROM wp_posts WHERE post_author = wp_users.ID) 
  + (SELECT SUM( comment_karma ) FROM wp_comments WHERE user_id = wp_users.ID) 
  as votes_and_karma
FROM wp_users

Or with subqueriesin the FROM clause:

SELECT 
  ID, 
  user_login, 
  user_email,
  wp_posts_group.sum_no_votes
  + wp_comments_group.sum_comment_karma
  as votes_and_karma
FROM wp_users
  left outer join 
    (SELECT 
       post_author,
       SUM(no_votes) as sum_no_votes
     FROM wp_posts 
     GROUP BY post_author) wp_posts_group
    ON wp_posts_group.post_author = wp_users.ID
  left outer join 
    (SELECT 
       user_id,
       SUM(comment_karma) as sum_comment_karma
     FROM wp_comments 
     GROUP BY user_id) wp_comments_group
    ON wp_comments_group.user_id = wp_users.ID


Can't be sure without testing it against your data, but something like this should get you started:

SELECT 
    wp_users.ID, 
    wp_users.user_login, 
    wp_users.user_email,
    SUM(wp_posts.no_votes),
    SUM(wp_comments.comment_karma)
FROM 
    wp_users 
    left join wp_posts on post_author = wp_users.ID 
    left join wp_comments on user_id = wp_users.ID 
group by
    wp_users.ID,
    wp_users.user_login,
    wp_users.user_email


I'll accept Stefan's Answer as final because he pointed me to the right direction. After messing around with it I came out with the following, which by the way, fits exactly to my needs:

SELECT ID, user_login, user_email, (
(
SELECT SUM( no_votes )
FROM wp_posts
WHERE post_author = wp_users.ID
) + (
SELECT SUM( comment_karma )
FROM wp_comments
WHERE user_id = wp_users.ID )
) AS total
FROM wp_users
ORDER BY total DESC 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜