2016-04-30 58 views
0

我有一個PostgreSQL 9.4.1表,像這樣...PostgreSQL的。基於「用戶名」欄重新排序行字母descendat

--------+-----------+-----------+---------------- 
serial | username | userprod | prodprice 
--------+-----------+-----------+---------------- 
1  | Zack  | candy | 44$ 
2  | Tom  | shoes | 54$ 
3  | Steve | pants | 23$ 
4  | Paul  | hood  | 65$ 
5  | John  | cap  | 23$ 
6  | Zack  | tshirt | 56$ 
7  | Tom  | pullover | 21$ 
8  | Steve | socks | 42$ 
9  | Paul  | shorts | 23$ 
10  | John  | masc  | 21$ 

行由串行列排序, 我怎麼能顯示同一個表,但是,基於「用戶名」列按字母順序降序對所有行進行重新排序?我希望Postgres能夠在單獨的桌面上實時自動執行此操作。我想我可以使用視圖?我怎樣才能做到這一點?

+1

閱讀關於'ORDER BY'子句:http://www.w3schools.com/sql/sql_orderby.asp – krokodilko

+2

表中的行不是***「排序」。您在不使用'order by'時看到的任何訂單純屬巧合。如果您想要查看它們,請在選擇時使用'order by'。這是隻有***才能獲得有保證的訂單。 http://www.postgresql.org/docs/current/static/sql-select.html#SQL-ORDERBY –

+0

創建視圖怎麼辦?可以自動完成? – litu16

回答

1

當然,您可以使用VIEW來返回有序的行。

CREATE VIEW v_tbl_username AS 
TABLE tbl ORDER BY username; 

,另一個用於您的行由serial列排序:

CREATE VIEW v_tbl_serial AS 
TABLE tbl ORDER BY serial; 

@a_horse's comment解決您的基本誤解。

該訂單將保留,除非它被外部查詢中的另一個ORDER BY否決。

視圖與early binding一起使用:僅包含在創建時出現的列。 SELECT * FROM tblTABLE tbl已解析爲當前現有列的列表。如果稍後更改了基礎表,那麼它不會自動級聯到視圖。

+0

謝謝erwin,我知道我可以使用'SELECT * FROM tbl_ ORDER BY ircusername ASC,stmtserial ASC;'我只是不知道如何創建它到VIEW – litu16