mysql查询到三个表,想用JOIN代替子查询

时间:2010-10-06 23:20:25

标签: sql mysql join subquery

我想使用join而不是子查询来查找在ip上过滤的trade_log上不存在的交易ID以及下面的mysql语法的当前日期。

SELECT plug.id as a,  
       plug.url as b,  
       trade.id as c  
  FROM plug, trade  
 WHERE trade.id = plug.trade_id  
   AND trade.id NOT IN (SELECT trade_log.trade_id 
                          FROM trade_log 
                         WHERE trade_log.ip = '".$ip."' 
                           AND trade_log.log_date = CURDATE())  
   AND trade.status = 1     
   AND plug.status = 1  
ORDER BY plug.weight DESC  
   LIMIT 1

请帮帮我......

2 个答案:

答案 0 :(得分:3)

使用:

   SELECT p.id as a,
          p.url as b,
          t.id as c
     FROM PLUG p
     JOIN TRADE t ON t.id = p.trade_id
                 AND t.status = 1
LEFT JOIN TRADE_LOG tl ON tl.trade_id = t.id
                      AND tl.ip = mysql_real_escape_string($ip)
                      AND tl.log_date = CURDATE()
    WHERE p.status = 1
      AND tl.ip IS NULL
 ORDER BY p.weight DESC
    LIMIT 1

答案 1 :(得分:0)

与OMG小马相同:

SELECT p.id as a,
p.url as b,
t.id as c
FROM plug p
INNER JOIN trade t ON (t.id = p.trade_id AND t.status = 1)
LEFT JOIN trade_log l ON (l.trade_id = t.id AND l.ip = '".$ip."' AND l.log_date = CURDATE())
WHERE p.status = 1 AND l.trade_id IS NULL
ORDER BY p.weight DESC
LIMIT 1