doutang1856 2014-07-24 13:24
浏览 14
已采纳

mysql中的多表查询

I am trying to query 4 tables(it works well when I query first 3 tables) and my table structure looks like,

1 Table - category

catid   catname
1       AAA
2       BBB

2 Table - questions

quid   qtype
1      data
2      
3      data

3 Table - answers

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

4 Table - concerns

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

Now my query is(with 3 tables)

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

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.

  • 写回答

3条回答 默认 最新

  • dongqian9013 2014-07-24 13:30
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错