【问题标题】:mysql right join 2 tables and select all in table1mysql右连接2个表并在table1中全选
【发布时间】:2019-01-08 08:22:47
【问题描述】:

我在数据库中使用两个表并查询表如下:

表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 AND image.type = 'm6-2' 如果图像 m6-2 没有我想要显示 NULL:

     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

如何编写命令?

【问题讨论】:

    标签: mysql join right-join


    【解决方案1】:

    当它们为 NULL 时,您需要修改您的 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
    

    【讨论】:

      【解决方案2】:

      您可以在下面尝试 - 使用将您的其他条件放在 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'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-06-22
        • 1970-01-01
        • 2020-02-29
        • 2015-05-30
        • 1970-01-01
        • 1970-01-01
        • 2020-12-15
        • 1970-01-01
        相关资源
        最近更新 更多