2011-12-25 83 views
2

我有2代表的列是这样的:MySQL的子查询(或UNION?)

Table1 
    testID username topic information  totalTime 
Table2 
    questionID testID question choices  answers 

我想选择一个测试用partiular testID从表1的问题,所有列和#NUMBER与来自同一testID表2,因此所得到的表应该是这样的:

testID username topic information  totalTime questionCount 

testID & questionID是主键。

我怎样才能形成这个查询?谢谢。

+1

你有没有尝试过自己什么了吗? – Bojangles 2011-12-25 14:08:14

回答

2

你可以这样说:

Select t1.testID, t1.username, t1.topic, t1.information, t1.totalTime, 
    (select count(questionID) from table2 t2 where t2.testID = t1.testID) as 'questionCount' 
from table t1 
1

也许我失去了一些东西,但不是我们谈论的是一个直接的加入?

select t1.testID, t1.username, t1.topic, t1.information, t1.totalTime 
     ,count(t2.questionID) AS questionCount 
from table1 t1 
    ,table2 t2 
where t1.testID = t2.testID 
    and t1.testID = :myInputTestID 
group by t1.testID, t1.username, t1.topic, t1.information, t1.totalTime