我正在尝试像这样的左外连接
SELECT records.some_id FROM forms
LEFT OUTER JOIN records
ON forms.form_id = records.form_id
ORDER BY records.some_id
这将从表格中获取所有结果:表格,包括某些不存在records.form_id的表格。但是,返回的结果在开头有不匹配的行,我怎么能在最后得到它们?
目前的结果:
NULL
NULL
5
20
100
预期是:
5
20
100
NULL
NULL
答案 0 :(得分:3)
使用case
。一般来说你可以做到
SELECT records.some_id FROM forms
LEFT OUTER JOIN records
ON forms.form_id = records.form_id
ORDER BY case when records.some_id is not null
then 1
else 2
end,
records.some_id
,特别是在MySQL中,您也可以
SELECT records.some_id FROM forms
LEFT OUTER JOIN records
ON forms.form_id = records.form_id
ORDER BY records.some_id is not null,
records.some_id
答案 1 :(得分:0)
同时加入COALESEC可能会有所帮助
SELECT records.some_id FROM forms
LEFT OUTER JOIN records
ON forms.form_id = records.form_id
ORDER BY COALESCE(records.some_id,-1) DESC