简体   繁体   中英

MYSQL customizable join and select

i want to use JOIN categories c ON c.id = i.category if post_type is 1 and i want to have c.title AS category_name, in SELECT otherwise JOIN categories c ON c.id = i.category and c.title AS category_name, must be not worked in query , i'm using case for join but my sql command is not correct. please help me. in all description my quastion means is how to change this below command to if post_type is 1 join must be not work

SELECT SQL_CALC_FOUND_ROWS
       i. * , 
       c.title AS category_name, 
       s.title AS status_title, 
       i.thumb_image, 
       CONCAT( u.name, ' ', u.family ) AS author
FROM contents i
LEFT JOIN categories c 
  ON i.category = CASE post_type WHEN 1 then c.id END 
JOIN users u ON u.id = i.posted_by
JOIN status_topics s ON s.id = i.t_status
WHERE i.id = 2

I would always do the LEFT JOIN and put a condition on the column itself:

SELECT SQL_CALC_FOUND_ROWS
   i. * , 
   IF(i.post_type = 1, c.title, NULL) AS category_name, 
   s.title AS status_title, 
   i.thumb_image, 
   CONCAT( u.name, ' ', u.family ) AS author
FROM contents i
LEFT JOIN categories c ON i.category = c.id
JOIN users u ON u.id = i.posted_by
JOIN status_topics s ON s.id = i.t_status
WHERE i.id = 2

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