MySQL子查询(或联合?)
我有两个列如下的表:MySQL子查询(或联合?),mysql,sql,Mysql,Sql,我有两个列如下的表: Table1 testID username topic information totalTime Table2 questionID testID question choices answers testID username topic information totalTime questionCount Select t1.testID, t1.username, t1.topic,
Table1
testID username topic information totalTime
Table2
questionID testID question choices answers
testID username topic information totalTime questionCount
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中选择一个测试的所有列,并从表2中选择具有相同测试ID的问题数,因此生成的表应该如下所示:
Table1
testID username topic information totalTime
Table2
questionID testID question choices answers
testID username topic information totalTime questionCount
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
testID和questionID是主键
如何形成此查询?谢谢。您可以这样做:
Table1
testID username topic information totalTime
Table2
questionID testID question choices answers
testID username topic information totalTime questionCount
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
也许我在这里遗漏了什么,但我们不是在谈论直接加入吗
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
你自己试过什么了吗?