简体   繁体   English

mysql中的多表查询

[英]multiple table query in mysql

I am trying to query 4 tables(it works well when I query first 3 tables) and my table structure looks like, 我正在尝试查询4个表(查询前3个表时效果很好),并且我的表结构如下所示:

1 Table - category 1张桌子-类别

catid   catname
1       AAA
2       BBB

2 Table - questions 2表-问题

quid   qtype
1      data
2      
3      data

3 Table - answers 3张桌子-答案

ansid   quid   catid   userid   answer
1       1      1       1        test1
2       2      1       1        test2
3       3      2       1        test3

4 Table - concerns 4表-关注

concern_id   catid   userid   ansid
1            1       1        1
2            1       4        3

Now my query is(with 3 tables) 现在我的查询是(3个表)

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

And it gives me(which is fine) 它给了我(很好)

catname   quid   catid   ansid   answer
AAA       1      1       1       test1
BBB       3      2       3       test3

Now I want to include the 4th table in the query and the resultant should look like 现在,我想在查询中包含第4个表,结果应类似于

concern_id   catname   quid   catid   ansid   answer
1             AAA       1      1       1       test1
null          BBB       3      2       3       test3

And here I am stuck with the query. 在这里,我坚持查询。

Try this: 尝试这个:

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

You need to use joins: 您需要使用联接:

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

Its not necessary to use joins. 不必使用连接。 MySQL will compile the joined version to the same result as this version. MySQL将编译加入的版本,使其结果与此版本相同。

I think you should combine them by ansid. 我认为您应该将它们合并在一起。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM