在同一个查询中获得用户群平均投票和个人用户投票?

时间:2010-05-19 05:12:34

标签: mysql sorting

这里是:

T1
[id] [desc]
 1    lovely
 2    ugly
 3    slender

T2
[id] [userid] [vote]
 1      1       3
 1      2       5
 1      3       2
 2      1       1
 2      2       4
 2      3       4

在一个查询中(如果可能)我想返回:

T1.id, T1.desc, AVG(T2.vote), T2.vote (for user viewing the page)

我可以通过以下方式获得前3项:

SELECT T1.id, T1.desc, AVG(T2.vote)
FROM T1
LEFT JOIN T2 ON T1.id=T2.id
GROUP BY T1.id

我可以通过以下方式获得第一,第二和第四项:

SELECT T1.id, T1.desc, T2.vote
FROM T1
LEFT JOIN T2 ON T1.id=T2.id
WHERE T2.userid='1'
GROUP BY T1.id

但我不知道如何在一个查询中获取所有四个项目。我尝试插入一个选择作为第四个术语:

SELECT T1.id
     , T1.desc
     , AVG(T2.vote)
     , (SELECT T2.vote 
          FROM T2 
         WHERE T2.userid='1') AS userVote 
   etc 
   etc

但我收到select returns more than one row...

的错误

帮助?

我希望在一个查询而不是两个查询中执行此操作的原因是我希望能够在MySQL中对数据进行排序,而不是将其拆分为多个数组。

2 个答案:

答案 0 :(得分:1)

使子查询与整体查询相关联。我想这就是你想要的:

SELECT t1.id, t1.descr, AVG(t2.vote),
   (SELECT t2.vote FROM t2 WHERE t2.userid = 1 AND t1.id = t2.id) AS uservote
FROM t1
LEFT JOIN t2 USING (id)
GROUP BY t1.id

我得到的结果是:

+------+---------+--------------+----------+
| id   | descr   | AVG(t2.vote) | uservote |
+------+---------+--------------+----------+
|    1 | lovely  |       3.3333 |        3 |
|    2 | ugly    |       3.0000 |        1 |
|    3 | slender |         NULL |     NULL |
+------+---------+--------------+----------+
3 rows in set (0.00 sec)

答案 1 :(得分:0)

我认为就是这样:

SELECT T1.id, T1.desc, T3.avgVote, T2.vote
FROM T1
  LEFT OUTER JOIN
    (SELECT id, AVG(vote) AS avgVote FROM T2)
    AS T3 ON T1.id=T3.id
  LEFT OUTER JOIN
    T2 ON T1.id=T2.id AND T2.userid=<UserID>