所以我的語法在所有三種情況下顯然是正確的(PostgreSQL並沒有對任何東西感興趣),但結果以所有這三種查詢的相同順序返回。甚至更奇怪的是,當我從下面的任何一個添加/刪除DESC時,它也沒有影響。是否可以根據子查詢的元素對結果進行排序?子查詢和排序? (ORDER BY)
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條件對結果順序沒有影響。
********* UPDATE:
我最終什麼事是使用陣列列在我看來,(在這種情況下articles_view)做我的所有排序做。這樣我就可以在主要查詢中的「列」上完成所有工作,完全避免使用JOINS。定義視圖的方式是,所有與人員/狀態表中的給定pubid(主鍵)匹配的列(都具有1->多個)存儲在視圖中的數組列中。我與排序查詢看起來是這樣的:
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),是主要的作者(或主要地位),這是我需要排序。
呃這就是我害怕的,我真的想避免使用連接(產品會變得太大,因此使用子查詢來代替)。 – 2009-08-19 23:23:08
使用內部聯接您只會得到合適的結果,並且查詢優化器應該確定一個計劃,在應用聯接之前刪除不滿足where子句的任何內容。 – 2009-08-19 23:30:25