简体   繁体   中英

MYSQL - JOIN the 1 table or the other table depending if there is a match

I have a table called events and I am doing a select on this table to display a grid with the select results.

The events table has a column called s_code . The s_code value comes from either the suppliers or members table.

How would I do a single JOIN that checks the suppliers and members table to get the code's name without having to do a LEFT JOIN on both members and suppliers tables like my query below. Basically I only want to have b.s_name where I have both b.s_name and c.s_name at the moment.

SELECT a.s_id, b.s_name, c.s_name, a.s_date, 
       a.s_description, d.s_name, a.s_actiondate,    
       e.s_name, a.s_emailed, a.s_status 
  FROM events AS a 
     LEFT JOIN members   AS b ON a.s_code = b.s_code 
     LEFT JOIN suppliers AS c ON a.s_code = c.s_code 
     LEFT JOIN webuser   AS d ON a.s_userid = d.s_ai 
     LEFT JOIN webuser   AS e ON a.s_actionuserid = e.s_ai 
 WHERE a.s_status = 'A' 
   AND a.s_userid = '1' 
   AND a.s_transactionstatus = 'A'

刚刚凝聚的两列进一个,如果第一个是非零回报,否则第二;

SELECT a.s_id, COALESCE(b.s_name, c.s_name) s_name, a.s_date, ...

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