这个MYSQL查询有什么问题

时间:2011-03-18 06:25:38

标签: java mysql subquery

    SELECT * FROM event JOIN user ON event.event_user_id=user.user_id
  WHERE ((event.event_date BETWEEN '2011-03-01' AND '2011-04-01' ) 
    AND user.user_id in (SELECT user_id FROM user_map 
      WHERE (user_map.user_id_map=1 AND user_map.user_relation<=7)));

这在Toad / MYsql中运行正常,但是当我在java + mysql驱动程序中使用预处理语句执行时失败

    SELECT * FROM event JOIN user ON event.event_user_id=user.user_id
  WHERE ((event.event_date BETWEEN ? AND ? ) 
    AND user.user_id in (SELECT user_id FROM user_map 
      WHERE (user_map.user_id_map=? AND user_map.user_relation<=?)));

...

pstmt.setDate(1, <sqlDate>);
pstmt.setDate(2, <sqlDate>);
pstmt.setLong(3, <int>);
pstmt.setLong(4, <int>);

pstmt.executeQuery();

1 个答案:

答案 0 :(得分:1)

它与问题没有密切关系,但查询效率不高,可以改进

SELECT * 
FROM   event 
       JOIN USER 
         ON event.event_user_id = USER.user_id 
       JOIN user_map 
         ON user_map.user_id = USER.user_id 
            AND user_map.user_id_map = 1
            AND user_map.user_relation<=7 
WHERE  ( event.event_date BETWEEN '2011-03-01' AND '2011-04-01' ) 
GROUP  BY USER.user_id 

你需要索引

  • (event.event_user_id,event.event_date)
  • (USER.user_id)
  • (user_map.user_id,user_map.user_id_map,user_map.user_relation)