Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MySQL子查询(或联合?)_Mysql_Sql - Fatal编程技术网

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

你自己试过什么了吗?