0
這裏是我的項目表:PG:左連接上表中把第一零記錄
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
,這裏是我的rating_cache表:
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_c沒有匹配的記錄項目疼痛表甚至在最高平均值之前出現。對於例如: 項目:
id name
1 A
2 B
3 C
rating_caches:查詢
id cacheable_id avg
1 3 3.0
2 2 2.5
結果如下:
id name
1 A
3 C
2 B
不宜與ID項目= 1放在最後?
沒問題。但爲什麼會發生這種情況呢?不應該是空值最後?即使doc示例首先將空值置爲空值http://www.postgresql.org/docs/8.1/static/tutorial-join.html – sonalkr132
空值在mysql和sqlite中最後成爲默認值。爲什麼PG必須有所不同? – sonalkr132
@ sonalkr132。 。 。具有諷刺意味的是,Postgres和SQL Server具有相同的行爲。不幸的是,SQL Server尚未支持'NULLS FIRST' /'NULLS LAST'語法。 –