MySQL条件连接使用相同的表

时间:2011-08-08 18:50:12

标签: mysql join conditional

我想使用LEFT JOIN执行以下操作(请不要建议UNION ALL

  SELECT o.*, s.col1, s.col2 FROM order o 
    INNER JOIN user u ON o.user_id = u.id

   IF o.date less than '2011-01-01'
      JOIN subscribe s ON u.key = s.key
   ELSE
       JOIN subscribe s ON u.email = s.email
   END IF;

我使用了以下但无法测试它。

SELECT o.*, COALESCE(s1.col1,s2.col1) AS 
   col1, COALESCE(s1.col2, s2.col2) AS col2
     FROM order o INNER JOIN user u ON o.user_id = u.id
     LEFT JOIN subscribe s1 ON 
     (u.key LIKE (CASE o.date >= '2011-01-01 00:00:00' 
                      WHEN TRUE THEN s1.key ELSE NULL END))
      LEFT JOIN subscribe s2 ON (u.email LIKE (CASE o.date < 
      '2011-01-01 00:00:00' WHEN TRUE THEN s.email 
       ELSE NULL END));

如果我错了,请纠正我。

感谢。

1 个答案:

答案 0 :(得分:5)

你不需要加入两次,就像这样:

SELECT o.*, s.col1, s.col2
   FROM order o INNER JOIN user u ON o.user_id = u.id
   LEFT JOIN subscribe s ON( ( o.date < '2011-01-01' AND u.key = s.key ) OR
                             ( o.date >= '2011-01-01' AND u.email = s.email ) )

如果您在subscribe.keysubscribe.email上有索引,则此解决方案不会执行全表扫描:

SELECT * FROM
(
   ( SELECT 0 AS mode, o.date AS odate, o.*, s.col1, s.col2
      FROM order o INNER JOIN user u ON o.user_id = u.id
      LEFT JOIN subscribe s ON( u.key = s.key ) )
   UNION
   ( SELECT 1 AS mode, o.date AS odate, o.*, s.col1, s.col2
      FROM order o INNER JOIN user u ON o.user_id = u.id
      LEFT JOIN subscribe s ON( u.email = s.email ) )
)
WHERE ( odate < '2011-01-01' AND mode = 0 ) OR
      ( odate >= '2011-01-01' AND mode = 1 )