使用内部联接对单个查询进行多个SQL查询

时间:2012-06-28 15:01:09

标签: java sql join

我有这个java代码:

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

2 个答案:

答案 0 :(得分: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个参数,或者您无法发送任何参数。

答案 1 :(得分: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 = ?