简体   繁体   中英

MySQL conditional join using the same table

I want to do the following using a LEFT JOIN (please do not suggest 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;

I used the following but can't test it.

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));

Please correct me if I am wrong.

Thanks.

You don't need to JOIN twice, do it like this:

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 ) )

And here is a solution that will not do a full table scan if you have indexes on subscribe.key and subscribe.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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM