简体   繁体   English

MYSQL-联接1个表或另一个表(取决于是否存在匹配项)

[英]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. 我有一个称为events的表,正在对此表进行选择以显示带有选择结果的网格。

The events table has a column called s_code . events表中有一列称为s_code The s_code value comes from either the suppliers or members table. s_code值来自suppliers表或members表。

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. 我将如何执行单个JOIN检查suppliersmembers表以获取代码的名称,而不必像下面的查询那样对memberssuppliers表都进行LEFT JOIN Basically I only want to have b.s_name where I have both b.s_name and c.s_name at the moment. 基本上,我只想拥有b.s_name ,而此时我同时拥有b.s_namec.s_name

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, ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 mysql查询取决于其他表 - mysql query depending on other table 如何在MySQL中联接层次表(表联接其他表,联接其他表,联接其他表)? - How to join hierarchical table in MySQL (table joins other table that joins other table that joins other table)? MySQL从表中选择取决于其他表值 - MySQL select from table depending to other table values 根据其他表的条件计算MySQL表中的行数 - Count the number of rows in MySQL table with criteria depending on other table 连接 Function 用于将一个表中的字段值与另一表匹配 - Join Function used to match value of field in one table with other table mysql-将一个表与另外两个表联接 - mysql - join one table with two other tables MYSQL MULTITABLE TABLE JOIN使用模式匹配/ JOIN - MYSQL MULTIPLE TABLE JOIN USING pattern match / JOIN MYSQL连接具有相同字段值的两个表字段,但如果另一个字段与另一个字段不匹配,则仍将包括 - MYSQL Join two table fields with same field value but will still include if the other field doesn't match the other one mysql如何根据一个字段和另一个表中的一个字段显示表的某些行? - mysql how to show some rows of table depending on one field and depending on one field in other table? 如何在MySQL中根据其他列自动更新表的列? - How to update a column of a table depending on the other column automatically in MySQL?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM