MySql根据字段值连接表

时间:2015-08-06 18:55:17

标签: mysql join

是否可以做这样的事情:

SELECT 
  p.*, u.*
FROM
  posts AS p 
  IF(p.status = 1) 
  LEFT JOIN users AS u 
    ON u.id = p.user_id 
    ELSE 
  LEFT JOIN pusers AS u 
    ON u.id = p.user_id 
WHERE p.id = 10 ;

根据帖子状态为true / false加入users / pusers表

1 个答案:

答案 0 :(得分:1)

不,但你可以这样做:

SELECT p.*,
       (case when p.status = 1 then u.col1 else pu.col1 end) as col1
FROM posts p LEFT JOIN
     users u 
     ON u.id = p.user_id and p.status = 1 LEFT JOIN
     pusers AS pu 
     ON pu.id = p.user_id and p.status <> 1
WHERE p.id = 10 ;

换句话说,您可以根据条件连接两个表并使用表中的值。