2012-06-28 133 views
0

我有這個java代碼:多個SQL查詢單查詢加盟

ArrayList<MessageMap> ids = getNewMail(UserID, type, maxIdMessage); 
Message[] message = new Message[ids.size()]; 
if(ids.size()>0){ 
    ResultSet rs; 
    int j =0; 
    for(MappaMessaggi i : ids){ 
     pstmt = conn.prepareStatement("SELECT * FROM Messaggi WHERE MessageID = ?"); 
     pstmt.setInt(1, i.getMessageID()); 
     rs = pstmt.executeQuery(); 
     rs.next(); 
     . 
     . 
     . 
    } 

其中getNewMail是:

public synchronized ArrayList<MessageMap> getNewMail(int UserID,int type,int max){ 
    ArrayList<MessageMap> map = new ArrayList<MessageMap>(); 
    try { 
     pstmt = conn.prepareStatement("SELECT * FROM MessageMap WHERE UserID = ? AND TipoID = ? AND MessageID > ?"); 
     . 
     .//fill arraylist with resultSet 
     . 
} 

我知道這是有可能做同樣的只有一個查詢,但我不知道如何......有人能睜開我的眼睛嗎? :) 謝謝!!!

編輯:我嘗試:

SELECT i.* 
FROM Messaggi AS i 
INNER JOIN MessageMap AS p i.MessageID = p.MessageID 
WHERE p.MessageID = 1 AND p.UserID = 1 AND p.TipoID = 2 

但我取回:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'i.MessageID = p.MessageID WHERE p.MessageID = 1 AND p.UserID = 1 AND p.TipoID = ' at line 3 

回答

1

試試這個:

SELECT i.*, p.* 
FROM Messaggi i 
INNER JOIN MessageMap p ON i.MessageID = p.MessageID 
WHERE i.MessageID = ? AND p.UserID = ? AND p.TipoID = ? 
+0

請參閱編輯頁:(我有錯誤 – JackTurky

+0

@JackTurky,對不起,我忘了'ON',看我的編輯。它應該是'INNER JOIN MessageMap p ON i.MessageID = p .MessageID'而不是'INNER JOIN MessageMap p i.MessageID = p.MessageID'。 –

+0

好!!!這是我需要的!謝謝!:) – JackTurky

1

根據你的問題和疑問,簡單的解決方案,我覺得可能是這個查詢(也許還有另外的列那涉及您的表)

SELECT A.* 
FROM MessageMap A 
    INNER JOIN Message B on A.MessageId = B.MessageId 
WHERE 
    A.UserId = ? 
    AND A.TipoID = ? 
    AND A.MessageId = ? 

另外,請或指定,如果你需要的3個參數你可以不發送他們中的任何一個。

+0

可能只是'Messaggi *'是誠實的。 – MatBailie

+0

請參閱編輯頁:(我有錯誤 – JackTurky