Sql pg:表上的左连接首先放置nil记录
这是我的项目表:Sql pg:表上的左连接首先放置nil记录,sql,postgresql,Sql,Postgresql,这是我的项目表: Column | Type | Modifiers | Storage | Stats target | Description ------------+-----------------------------+-------------------------------------------------------+-----
Column | Type | Modifiers | Storage | Stats target | Description
------------+-----------------------------+-------------------------------------------------------+----------+--------------+-------------
id | integer | not null default nextval('projects_id_seq'::regclass) | plain | |
name | character varying(255) | | extended | |
repo_id | integer | | plain | |
created_at | timestamp without time zone | | plain | |
updated_at | timestamp without time zone | | plain | |
user_id | integer | | plain | |
data_path | character varying(255) | | extended | |
private | boolean | default false | plain | |
uniqueurl | character varying(255) | | extended | |
urlbase | character varying(255) | | extended | |
ancestry | character varying(255) | | extended | |
deleted_at | timestamp without time zone | | plain | |
Indexes:
"projects_pkey" PRIMARY KEY, btree (id)
"index_projects_on_name_and_user_id" UNIQUE, btree (name, user_id)
"index_projects_on_ancestry" btree (ancestry)
"index_projects_on_deleted_at" btree (deleted_at)
Has OIDs: no
这是我的分级缓存表:
Column | Type | Modifiers | Storage | Stats target | Description
----------------+-----------------------------+------------------------------------------------------------+----------+--------------+-------------
id | integer | not null default nextval('rating_caches_id_seq'::regclass) | plain | |
cacheable_id | integer | | plain | |
cacheable_type | character varying(255) | | extended | |
avg | double precision | not null | plain | |
qty | integer | not null | plain | |
dimension | character varying(255) | | extended | |
created_at | timestamp without time zone | | plain | |
updated_at | timestamp without time zone | | plain | |
Indexes:
"rating_caches_pkey" PRIMARY KEY, btree (id)
"index_rating_caches_on_cacheable_id_and_cacheable_type" btree (cacheable_id, cacheable_type)
Has OIDs: no
我在两个表上进行左外连接,包括:
SELECT "projects".* FROM "projects" LEFT OUTER JOIN rating_caches
ON rating_caches.cacheable_id = projects.id
WHERE "projects"."deleted_at" IS NULL ORDER BY rating_caches.avg desc
这将正确地对项目进行排序(最高平均值排在第一位),但是在rating_caches表中没有匹配记录的项目甚至排在最高平均值之前。例如:
项目:
id name
1 A
2 B
3 C
分级缓存:
id cacheable_id avg
1 3 3.0
2 2 2.5
查询结果如下所示:
id name
1 A
3 C
2 B
id=1的项目不应该排在最后吗?只需使用
NULLS last
:
ORDER BY rating_caches.avg desc NULLS LAST
请注意,指定了:
可以使用NULLS FIRST
和NULLS LAST
选项来确定
在排序中,空值是出现在非空值之前还是之后
订购。默认情况下,空值排序时好像大于任何非空值
价值也就是说,NULLS FIRST
是DESC
顺序的默认值,NULLS
最后
否则
好的,这样行。但为什么会这样呢?空值不应该最后出现吗?在mysql和sqlite中,即使是doc示例也会将空值放在第一位,空值作为默认值放在最后。为什么pg必须与众不同?@sonalkr132。讽刺的是,在这种情况下,Postgres和SQL Server具有相同的行为。不幸的是,SQL Server(尚未)支持
NULLS FIRST
/NULLS LAST
语法。