2016-07-04 138 views
0
SELECT DISTINCT "Users"."id" , "Users".name, 
    "Users"."surname", "Users"."gender", 
    "Users"."dob", "Searches"."start_date" 
FROM "Users" 
    LEFT JOIN "Searches" ON "Users"."id" = "Searches"."user_id" 
WHERE (SQRT(POW(69.1 * ("Users"."latitude" - 45.465454), 2) + POW(69.1 * (9.186515999999983 - "Users"."longitude") * COS("Users"."latitude"/57.3), 2))) < 20 
    AND "Users"."status" = true 
    AND "Users"."id" != 18 
    AND "Searches"."activity" = \'clubbing\' 
    AND "Users"."gender" = \'m\' 
    AND "Users"."age" BETWEEN 18 AND 30 
ORDER BY ABS("Searches"."start_date" - date \'2016-07-07\') 

因爲某些原因上面的查詢將返回以下錯誤:Postgres的DISTINCT查詢問題

for SELECT DISTINCT, ORDER BY expressions must appear in select list 

我只想要返回唯一用戶,但我真的不知道什麼是錯。

感謝您的幫助

+0

錯誤信息中你不明白的是什麼? –

+0

@GordonLinoff我不知道該怎麼做,因爲我沒有看到任何錯誤。 start_date已經在SELECT列表 – Anonymous

+0

中。 。它可能需要整個表達式在'select'中。 –

回答

0

在Postgres裏,你可以使用DISTINCT ON讓每個用戶ID一行:

SELECT DISTINCT ON (u."id") u."id", u.name, u."surname", u."gender", u."dob", s."start_date" 
FROM "Users" u LEFT JOIN 
    "Searches" s 
    ON u."id" = s."user_id" 
WHERE (SQRT(POW(69.1 * (u."latitude" - 45.465454), 2) + POW(69.1 * (9.186515999999983 - u."longitude") * COS(u."latitude"/57.3), 2))) < 20 AND 
     u."status" = true AND 
     u."id" != 18 AND "Searches"."activity" = \'clubbing\' AND 
     u."gender" = \'m\' AND 
     u."age" BETWEEN 18 AND 30 
ORDER BY users.id, ABS(s."start_date" - date \'2016-07-07\'); 

通知表的別名如何使查詢更容易編寫和閱讀。

+0

現在我收到了這個錯誤:error:syntax error at or near「,」 – Anonymous

0

只要做錯誤信息說我會在SELECT列表中包含表達式ABS("Searches"."start_date" - date '2016-07-07')。無需更改您的查詢邏輯。
absdiffdate稍後可能會在處理結果時被丟棄。

SELECT DISTINCT "Users"."id" , "Users".name, 
    "Users"."surname", "Users"."gender", 
    "Users"."dob", "Searches"."start_date", 
    ABS("Searches"."start_date" - date '2016-07-07') absdiffdate 
FROM "Users" 
    LEFT JOIN "Searches" ON "Users"."id" = "Searches"."user_id" 
WHERE (SQRT(POW(69.1 * ("Users"."latitude" - 45.465454), 2) + POW(69.1 * (9.186515999999983 - "Users"."longitude") * COS("Users"."latitude"/57.3), 2))) < 20 
    AND "Users"."status" = true 
    AND "Users"."id" != 18 
    AND "Searches"."activity" = 'clubbing' 
    AND "Users"."gender" = 'm' 
    AND "Users"."age" BETWEEN 18 AND 30 
ORDER BY ABS("Searches"."start_date" - date '2016-07-07') 

可能將與更多的記錄這個新列結果時DISTINCT應用?
我不這麼認爲,因爲你正在從start_date減去一個常量,類似的start_date對應的結果類似。