2013-11-22 64 views
0

我有这个表,记录考试成绩为用户:东西,因为集团的MySQL查询怪BY语句

CREATE TABLE IF NOT EXISTS `ts` (
    `id` int(11) NOT NULL AUTO_INCREMENT, 
    `uid` int(11) NOT NULL, 
    `xid` int(11) NOT NULL, 
    `lid` int(11) NOT NULL, 
    `grade` double NOT NULL, 
    `duration` varchar(10) COLLATE utf8_turkish_ci NOT NULL, 
    `trues` int(11) NOT NULL DEFAULT '0', 
    `falses` int(11) NOT NULL DEFAULT '0', 
    `empties` int(11) NOT NULL DEFAULT '0', 
    PRIMARY KEY (`id`), 
    KEY `uid` (`uid`), 
    KEY `xid` (`xid`), 
    KEY `lid` (`lid`), 
) ENGINE=InnoDB; 

而且我有这个表中的记录:

|id|uid|xid|lid|grade|duration|trues|falses|empties|  
+--+---+---+---+-----+--------+-----+------+-------+ 
|45| 20| 1| 1| 80|00:01:12| 8|  2|  0| 
|46| 20| 1| 2| 40|00:02:31| 4|  6|  0| 
|47| 20| 3| 1| 100|00:01:10| 1|  0|  0| 
|48| 20| 4| 1| 83|00:00:51| 5|  1|  0| 
|49| 20| 2| 1| 0|00:00:02| 0|  1|  0| 
|53| 20| 4| 2| 50|00:00:04| 1|  1|  0| 
|54| 20| 1| 2| 50|00:00:41| 5|  5|  0| 

lid指示由xid表示的考试难度级别。我想以独特的水平展示每个独特考试的最高成绩。例如有7行。和id [46]和id [54]适用于相同的考试和级别。所以我必须在这两行中列出更高等级的值。

我已经做了查询:

SELECT 
     failed.fgrade, 
     succeeded.sgrade, 
     ts.xid, 
     ts.lid, 
     ts.trues, 
     ts.falses, 
     ts.empties, 
     MAX(`grade`) AS grade, 
     ts.duration, 
     x.exam 
FROM 
     ts 
JOIN 
     x ON ts.xid = x.id 
JOIN 
     (SELECT 
      COUNT(DISTINCT(xid)) AS sgrade 
     FROM ts 
     WHERE uid = 20 AND grade >= 70) AS succeeded 

JOIN 
     (SELECT 
      COUNT(DISTINCT(xid)) AS fgrade 
     FROM ts 
     WHERE uid = 20 AND grade < 70) AS failed 

WHERE 
     ts.uid = 20 

GROUP BY 
     xid, 
     lid 
ORDER BY 
     ts.id 

当我运行查询时得到奇怪的结果:(!)

Exam Name Level Duration  True False Empty Total Grade fgrade sgrade 
Functions  1 00:00:02  0  1  0  1  0  3  3 
Numbers  2 00:02:31  4  6  0  10 50  3  3 (!) 
Equations  2 00:00:04  1  1  0  2 50  3  3 
Numbers  1 00:01:12  8  2  0  10 80  3  3 
Equations  1 00:00:51  5  1  0  6 83  3  3 
Functions  1 00:01:10  1  0  0  1 100  3  3 

如果你看一下在结果表中的行有什么奇怪的。 4个正确的答案和6个错误的答案可以得到40分。但它显示了其他行的等级值,同时显示了自己的真实和错误答案。

我基本上希望针对给定用户的每个难度级别(uid)显示所有不同的考试。现在,当我写这个问题时,我开始认为这可能是由于GROUP BY声明造成的。但是写这个问题需要一段时间。我不能删除这个。

+0

哪里'ON'为了你最后2加入?真的,为什么那些连在一起呢? –

回答

1

考虑下面两行:

|46| 20| 1| 2| 40|00:02:31| 4|  6|  0| 
|54| 20| 1| 2| 50|00:00:41| 5|  5|  0| 

当由XID基,盖只有一行被选择(第一行)

|46| 20| 1| 2| 40|00:02:31| 4|  6|  0| 

但对于最大(级),它是一种聚合功能,这意味着它会查找所有结果行获取最大值 - >最大(等级)回报50.
- >如果您在等级中选择了等级和最高等级,您将同时收到40和50.

在你的情况,我认为你应该加入两个TS表获得更高的价值等级是这样的:

select ts1.* from ts ts1 left join ts laster on ts1.xid = laster.xid and ts1.lid = laster.lid 
and ts1.uid = laster.uid and ts1.grade < laster.grade where isnull(laster.grade) 
+0

ts2是什么? – zkanoca

+0

抱歉,输入错误,ts2代表激光。 –