数据库
首页 > 数据库> > 当子查询返回0行时,MySQL查询不返回任何内容

当子查询返回0行时,MySQL查询不返回任何内容

作者:互联网

如果任何子查询都不返回任何行,则尝试从子查询中选择字段时,则不返回任何内容(甚至不返回空结果集)

SELECT sub1.field, sub2.another_field
    FROM (
        (
            SELECT field
            FROM table
            WHERE id=1
        ) AS sub1, (
            SELECT another_field
            FROM table
            WHERE id=2
        ) AS sub2
    )

我希望当子查询返回0行时包含NULL值的行.

解决方法:

您需要执行以下外部联接

SELECT sub1.field, sub2.another_field
FROM (
        SELECT field, id
        FROM tab1
        WHERE id=1
    ) AS sub1 LEFT OUTER JOIN (
        SELECT another_field, id
        FROM tab1
        WHERE id=2
    ) AS sub2
  ON sub1.id = 1 and sub2.id = 2

标签:subquery,mysql
来源: https://codeday.me/bug/20191201/2081757.html