2012-08-03 168 views
7

請幫我解決下一個oracle sql查詢問題。Oracle選擇子查詢

SELECT "NEWS"."NEWSID" as ID, 
     "NEWS"."SLUG", 
     "NEWS_TRANSLATION".*, 
     (SELECT FILENAME FROM NEWS_MEDIA WHERE NEWSID = ID AND rownum <= 1 ORDER BY POSITION ASC) as FILENAME 
FROM "NEWS" 
INNER JOIN "NEWS_TRANSLATION" ON NEWS.NEWSID = NEWS_TRANSLATION.NEWSID 
WHERE (NEWS.PUBLISH = 1) AND (NEWS_TRANSLATION.LANG = :lang) 
ORDER BY "NEWS"."NEWSID" DESC; 

當我執行此查詢我有錯誤

ORA-00907: missing right parenthesis 
00907. 00000 - "missing right parenthesis" 
*Cause:  
*Action: 
Error at Line: 4 Column: 74 
+1

如果意圖是從news_media獲取新聞項目的MIN位置的文件名,我認爲rownum沒有被正確使用。在選擇一條記錄後應用「ORDER BY」。它需要被subqueried,或者更好的是,與MIN(position)分開連接。見http://www.oracle.com/technetwork/issue-archive/2006/06-sep/o56asktom-086197.html – Glenn 2012-08-03 13:25:10

回答

9

試試這個:當您使用

​​

「排序依據」 和「 rownum「在一起,你需要先訂購它們並尋找第一個記錄。

1

請通過子句中的子查詢去除的順序嘗試。

+0

試過了,但我有同樣的錯誤。 – rtyshyk 2012-08-03 12:30:52

+0

從FILENAME中選擇FILENAME WHERE NEWSID = ID和rownum <= 1;我不確定列名ID,請確認。 – TechDo 2012-08-03 12:57:38

1

這裏是工作代碼

SELECT "NEWS"."NEWSID" as ID, 
    "NEWS"."SLUG", 
    "NEWS_TRANSLATION".*, 
    (SELECT FILENAME FROM NEWS_MEDIA WHERE NEWSID = ID AND rownum <= 1) as FILENAME 
FROM "NEWS" 
INNER JOIN "NEWS_TRANSLATION" ON NEWS.NEWSID = NEWS_TRANSLATION.NEWSID 
WHERE (NEWS.PUBLISH = 1) AND (NEWS_TRANSLATION.LANG = :lang) 
ORDER BY "NEWS"."NEWSID" DESC 
+0

相同'線路錯誤:4列:51' – rtyshyk 2012-08-03 13:12:17

+0

我在子查詢中將ID更改爲NEWS.NEWSID,所有工作都很好。但我怎麼可以用ORDER BY做到這一點? – rtyshyk 2012-08-03 13:15:24

+0

你想通過'order by'顯示什麼?它是否像'在你的問題中一樣? – Mistu4u 2012-08-03 13:19:47

1

試試這個:

SELECT "NEWS"."NEWSID" AS ID, "NEWS"."SLUG", "NEWS_TRANSLATION".*, 
     (SELECT FILENAME 
      FROM NEWS_MEDIA 
     WHERE NEWSID = "NEWS"."NEWSID" AND ROWNUM <= 1) 
      AS FILENAME 
    FROM  "NEWS" 
     INNER JOIN 
      "NEWS_TRANSLATION" 
     ON NEWS.NEWSID = NEWS_TRANSLATION.NEWSID 
WHERE (NEWS.PUBLISH = 1) AND (NEWS_TRANSLATION.LANG = :LANG) 
ORDER BY "NEWS"."NEWSID" DESC 
+0

當您的子查詢僅返回主查詢中的每個記錄的一個值時,那你爲什麼要嘗試對子查詢進行排序? – hmmftg 2012-08-03 13:19:26

+0

我回答你的問題在這裏http://stackoverflow.com/questions/11794242/oracle-select-with-subquery#comment15674817_11796362 – rtyshyk 2012-08-03 14:23:23

+0

@Pivasyk我的問題是:什麼是在子查詢排序的目的? – hmmftg 2012-08-03 15:34:33

-2
SELECT STUDENT_NAME, STUDENT_ALIAS_NAME 
FROM school 
WHERE STUDENT_NAME IN (
     SELECT STUDENT_NAME 
     FROM school 
     WHERE STUDENT_DEPARMENT= 0 
     ); 
+0

雖然這可能會回答這個問題,但請備份代碼,並說明它爲什麼會起作用以及爲什麼它比其他答案更好。 – 2014-07-10 06:26:25