首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >mysql中的多表查询

问mysql中的多表查询
EN

Stack Overflow用户
提问于 2014-07-24 13:24:20
回答 3查看 63关注 0票数 0

我正在尝试查询4个表(当我查询前3个表时,它运行得很好),而且我的表结构看起来像,

1表-类别

代码语言:javascript
复制
catid   catname
1       AAA
2       BBB

2表格-问题

代码语言:javascript
复制
quid   qtype
1      data
2      
3      data

3表-答案

代码语言:javascript
复制
ansid   quid   catid   userid   answer
1       1      1       1        test1
2       2      1       1        test2
3       3      2       1        test3

4表-关切事项

代码语言:javascript
复制
concern_id   catid   userid   ansid
1            1       1        1
2            1       4        3

现在我的查询是(有3个表)

代码语言:javascript
复制
SELECT category.catname,questions.quid,answers.catid,answers.ansid,answers.answer

FROM questions , answers ,category

where  questions.qtype = 'data' 

and questions.quid = answers.quid 

and category.catid = answers.catid 

and answers.userid = 1

它给了我(这很好)

代码语言:javascript
复制
catname   quid   catid   ansid   answer
AAA       1      1       1       test1
BBB       3      2       3       test3

现在,我希望在查询中包含第四个表,其结果应该如下所示

代码语言:javascript
复制
concern_id   catname   quid   catid   ansid   answer
1             AAA       1      1       1       test1
null          BBB       3      2       3       test3

在这里,我被这个问题困住了。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2014-07-24 13:30:59

试试这个:

代码语言:javascript
复制
SELECT category.catname,questions.quid,answers.catid,answers.ansid,answers.answer

FROM 
questions 
INNER JOIN answers  on (questions.quid = answers.quid )
INNER JOIN category cat on (category.catid = answers.catid)
LEFT JOIN concerns con on (concerns.userId = answers.userId and concerns.catid = answers.catid  AND concerns.ansid = answers.ansid )
where  questions.qtype = 'data' 

and answers.userid = 1
票数 1
EN

Stack Overflow用户

发布于 2014-07-24 13:31:21

您需要使用联接:

代码语言:javascript
复制
SELECT category.catname,questions.quid,answers.catid,answers.ansid,answers.answer

FROM category

join answers 
on category.catid = answers.catid 

join questions
on questions.quid = answers.quid

join concern
on concerns.userId = answers.userId and concerns.catid = answers.catid  AND      concerns.ansid = answers.ansid

where  questions.qtype = 'data' 
and answers.userid = 1
票数 1
EN

Stack Overflow用户

发布于 2014-07-24 13:33:22

没有必要使用联接。MySQL将将连接版本编译为与此版本相同的结果。

我觉得你应该把它们结合在一起。

代码语言:javascript
复制
SELECT concern.concern_id, category.catname, questions.quid, answers.catid, answers.ansid, answers.answer

FROM questions, answers, category, concerns

where questions.qtype = 'data' 

and concerns.ansid = answers.ansid

and questions.quid = answers.quid 

and category.catid = answers.catid 

and answers.userid = 1
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24935000

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档