当尝试从子查询中选择字段时,如果任何子查询没有返回任何行,则不返回任何内容(甚至不是空结果集)
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
值。
答案 0 :(得分:3)
您需要按如下方式进行外部联接
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
答案 1 :(得分:0)
要解决当所有子查询返回零行时查询整体返回的问题我将整个批量包装在UNION
中,空白行。
SELECT * FROM (
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
UNION
SELECT NULL, NULL
) AS t0