查询加入2个表的问题

时间:2012-07-20 07:57:06

标签: mysql

此查询未运行..请解决此问题..

select q.id,q.name,qq.text 
from quiz q,quiz_question qq 
where qq.quiz_id='1'

表:

quiz
   id,name
quiz_question
   id,quiz_id,text

4 个答案:

答案 0 :(得分:2)

您的查询没有问题。我打赌它会运行,但结果有误。您cross 加入表格。我想你想要:

select q.id, q.name, qq.text 
from   quiz q,quiz_question qq 
where qq.quiz_id = '1' AND
      q.id=qq.quiz_id

更好执行此操作

select q.id, q.name, qq.text 
from   quiz q INNER JOIN quiz_question qq 
           on q.id=qq.quiz_id
where  qq.quiz_id = '1'

还有一件事,如果您的 ID number,那么不应该用单引号包装

select q.id, q.name, qq.text 
from   quiz q INNER JOIN quiz_question qq 
           on q.id=qq.quiz_id
where  qq.quiz_id = 1

答案 1 :(得分:1)

select q.id,q.name,qq.text 
from quiz q inner join quiz_question qq on q.id = qq.quiz_id
where q.quiz_id='1';

OR

select q.id,q.name,qq.text 
from quiz q inner join quiz_question qq on q.id = qq.quiz_id and q.quiz_id='1';

答案 2 :(得分:0)

不要使用旧版SQL语法。如果要连接表,请使用expiclit join

select q.id, q.name, qq.text 
from quiz q
inner join quiz_question qq on q.id = qq.quiz_id
where q.id = 1

答案 3 :(得分:0)

您需要做的是在quiz_id上一起加入表格。

这可以这样做:

 SELECT
  q.id,q.name,
  qq.text
 FROM
  quiz q
  INNER JOIN quiz_question qq ON ( q.id = qq.quiz_id )
 WHERE
  q.id = 1