因此,我的语法在所有三种情况下显然都是正确的(PostgreSQL 没有抱怨任何事情),但是所有这三个查询的结果都以相同的顺序返回。当我从以下任何内容中添加/删除 DESC 时甚至更奇怪,它也没有影响。是否可以根据子查询的元素对结果进行排序?
Sort by affiliation
SELECT * FROM articles_view WHERE (1=1)
AND spubid IN
(SELECT people.spubid FROM people WHERE (people.slast ilike 'doe')
GROUP BY people.spubid, people.slast, people.saffil)
AND spubid IN
(SELECT status.spubid FROM status WHERE ((status.imonth >= 01 OR status.imonth IS NULL) AND status.iyear >= 2000) AND ((status.imonth <= 01 OR status.imonth IS NULL) AND status.iyear <= 2008) ORDER BY status.iyear, status.imonth)
Sort by last name, descending order
SELECT * FROM articles_view WHERE (1=1)
AND spubid IN
(SELECT people.spubid FROM people WHERE (people.slast ilike 'doe')
GROUP BY people.spubid, people.slast, people.saffil ORDER BY people.slast DESC)
AND spubid IN
(SELECT status.spubid FROM status WHERE ((status.imonth >= 01 OR status.imonth IS NULL) AND status.iyear >= 2000) AND ((status.imonth <= 01 OR status.imonth IS NULL) AND status.iyear <= 2008))
Sort by year/month descending order
SELECT * FROM articles_view WHERE (1=1)
AND spubid IN
(SELECT people.spubid FROM people WHERE (people.slast ilike 'doe')
GROUP BY people.spubid, people.slast, people.saffil )
AND spubid IN
(SELECT status.spubid FROM status WHERE ((status.imonth >= 01 OR status.imonth IS NULL) AND status.iyear >= 2000) AND ((status.imonth <= 01 OR status.imonth IS NULL) AND status.iyear <= 2008) ORDER BY status.iyear, status.imonth DESC)
我只是不确定为什么 ORDER BY 条件对结果的顺序没有影响。
********* 更新:
我最终做的是使用我的视图中的数组列(在本例中为articles_view)来完成我的所有排序。这样我就可以在主查询中的“列”上进行所有操作,并且完全避免使用 JOINS。定义视图的方式是,与人员/状态表中的给定 pubid(主键)匹配的所有列(都具有 1->many)存储在视图中的数组列中。我的排序查询如下所示:
SELECT * FROM articles_view WHERE
((articles_view.skeywords_auto ilike '%ice%') OR (articles_view.skeywords_manual ilike '%ice%'))
ORDER BY (articles_view.authors[1]).slast
这样做的原因是因为我总是知道数组的第一个成员(在 Postgres 中的第一个索引是 1 而不是通常的 0)是主要作者(或主要状态),这是我进行排序所需要的。