2017-05-29 51 views
0

我使用PostgreSQL WITHhttps://www.postgresql.org/docs/current/static/queries-with.html。我可以運行相當複雜的查詢,但是我可以使用已排序的數據嗎?例如:PostgreSQL WITH查詢已經選定的表

SELECT id, f_name, l_name, email FROM users 
WHERE f_name = 'BabyBoy' 

WITH i_need_do_thomething AS (
# and than use that filtered data 
) 
SELECT * FROM i_need_do_thomething 

感謝

UPDATE

,我在Ruby中使用此查詢on Rails的所有問題。我用聯想,如:

@laptop = Laptop.find(1) 
@laptop.user.do_custom_sql(HERE_WILL_BE_RAW_SQL) 

其中@laptop.user等於

SELECT id, f_name, l_name, email FROM users 
WHERE f_name = 'BabyBoy' 

回答

2

WITH QUERIES每個查詢都被視爲一個臨時表。您可以根據需要放置儘可能多的查詢:

WITH filtered_something AS (
    SELECT id, f_name, l_name, email FROM users WHERE f_name = 'BabyBoy' 
), i_need_do_something AS (
    SELECT * FROM filtered_something 
) 
SELECT * FROM i_need_do_something; 
+0

因此,我只能在單獨的情況下使用'WITH'?我不能像我在示例中所寫的那樣使用它。對? –

+0

是的,你不能這樣做。在這種情況下,我認爲你應該使用'ActiveRecord :: Base.connection.execute(whole_sql_here)',然後遍歷結果集。 –