mysql右键连接2个表并在表1中选择all

u0njafvf  于 2021-06-15  发布在  Mysql
关注(0)|答案(2)|浏览(267)

我在数据库中使用两个表,并查询如下所示的表:
student ```
id | studentid | name | room

  1  |    28778    |   a    |   1
  2  |    28779    |   b    |   2
  3  |    28785    |   c    |   2
  4  |    28300    |   d    |   2
  5  |    28301    |   e    |   2
  6  |    28302    |   f    |   2
  7  |    28303    |   g    |   2
  8  |    28304    |   h    |   3
  9  |    28305    |   i    |   3
 10  |    28306    |   j    |   3
表 `image` ```
id  |student_id|  image_filename  |  type  |
  ---------------------------------------------------
      1  |     1    |    qwrioqw.jpg   |  m6-1  |
      2  |     1    |    oerqew.jpg    |  m6-2  |
      3  |     2    |    qwwqeqw.jpg   |  m6-2  |
      4  |     4    |    wqeioqw.jpg   |  m6-1  |
      5  |     4    |    qwwoqeqw.jpg  |  m6-2  |
      6  |     7    |    eqwrioqw.jpg  |  m6-1  |
      7  |     7    |    rewtoqw.jpg   |  m6-2  |
      8  |     8    |    asdsadas.jpg  |  m6-2  |

我用了命令 SELECT name, id, image.image_filename, image.type FROM image RIGHT JOIN student ON student_id=student.id WHERE room=2 HAVING image.type = 'm6-2' ORDER BY id 此命令的结果是:

name  |  id  |  image_filename  |  type  |
  ---------------------------------------------------
        b  |  2   |    qwwqeqw.jpg    |  m6-2  |
        d  |  4   |    qwwoqeqw.jpg   |  m6-2  |
        g  |  7   |    rewtoqw.jpg    |  m6-2  |

但我想要所有的结果 student.room = 2 以及 image.type = 'm6-2' 如果图像m6-2为“无”,我希望显示空值:

name  |  id  |  image_filename  |   type
  -----------------------------------------------
        b  |  2   |    qwwqeqw.jpg   |   m6-2
        c  |  3   |        NULL      |   NULL
        d  |  4   |    rewtoqw.jpg   |   m6-2
        e  |  5   |        NULL      |   NULL
        f  |  6   |        NULL      |   NULL
        g  |  7   |    rewtoqw.jpg   |   m6-2

如何编写命令?

u1ehiz5o

u1ehiz5o1#

您可以尝试使用下面的-put your others condition on子句而不是where子句

SELECT name, id, image.image_filename, image.type 
    FROM image RIGHT JOIN student ON student_id=student.id 
    and room=2 and image.type = 'm6-2'
ct2axkht

ct2axkht2#

当image.type为空时,需要修改以获取image.type:

SELECT name, id, image.image_filename, image.type 
FROM image RIGHT JOIN student ON student_id=student.id 
WHERE room=2 and (image.type = 'm6-2' or image.type is null) 
ORDER BY id

相关问题