dtwk6019 2015-02-28 20:25
浏览 57
已采纳

从MySQL中的3个表中选择几个字段,但该字段不得要求存在于第三个表中

I have 3 tables named student, student_lessons and student_image. I want to select student, student lessons and display students image IF EXISTS. Is there anyway to handle it in one query ?

try to select student id, student name, student lesson (must exists) and student image path, student image pic_id if exists

# TABLE `students`
id | name | surname
1  : John : Malkovich
2  : John : Smith

# TABLE `students_lessons` ( no AI id here)
student_id | lesson | note
1          : math   : A
1          : geo    : B
2          : math   : C

# TABLE `students_image`
pic_id | student_id | image_path 
1      :  1         : some path       
2      :  1         : some path
3      :  2         : some path   

if I try to do query with joint, it return zero if it doesn't find any picture. How can I do query to select image if exists in single query ?

  • 写回答

1条回答 默认 最新

  • duansha7453 2015-02-28 20:32
    关注
    SELECT students.* 
    FROM students
    JOIN students_lessons ON (students_lessons.student_id = students.id)
    LEFT JOIN students_image ON (students_image.student_id = students.id)
    

    Or if you only care if image exists:

    SELECT students.* 
    FROM students
    JOIN students_lessons ON (students_lessons.student_id = students.id)
    WHERE EXISTS (
       SELECT si.* 
       FROM students_image si
       WHERE si.student_id = students.id
    )
    

    I think what you're looking for is a LEFT JOIN. Just modify the SELECT to your linking. This query selects all students and have lessons, wether they have an image or not.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题