合并同名列

时间:2019-01-06 04:46:08

标签: php mysql

所以我有两个表,它们以某种方式具有相同的列名。在结果查询中,我希望合并结果,然后将其占用一个空值。

这是我的表的结构:

  

位置

position

  

帐户

accounts

  

员工

employees

  

学生

students

  

ssc

ssc

  

名称

names

  

办公室

offices

这是我的代码:

SELECT app.approved, p.position, n.fname, n.mname, n.lname, o.office, e.signature, ssc.signature FROM approvals app LEFT JOIN positions p ON p.position_id = app.position_id LEFT JOIN accounts a ON a.account_id = app.account_id LEFT JOIN employees e ON e.account_id = a.account_id LEFT JOIN students s ON s.account_id = a.account_id LEFT JOIN ssc ON ssc.students_id = s.students_id AND ssc.removed = 0 LEFT JOIN names n ON n.name_id = s.name_id OR n.name_id = e.name_id LEFT JOIN offices o ON o.office_id = p.office_id WHERE app.event_id = '10'

实际结果是这样:

result

请注意,e.signature的某些行为空,而ssc.signature相同,因此,我希望将它们合并,顺便说一下,SSC永远不能在employees表中拥有其签名。

2 个答案:

答案 0 :(得分:1)

由于您知道要合并的那些列的名称,因此需要使用MySQL COALESCE()函数返回在提供的参数列表中找到的第一个非null值。

SELECT COALESCE(NULL, NULL, NULL, 'Aquaman', NULL, 'Some other dude');

这将返回Aquaman

实际上,您可以使用列名代替原始值。例如:

SELECT app.approved, COALESCE(e.signature, ssc.signature) AS signature;

请注意,AS signature部分不是必需的,但您应该可以为组合字段选择别名。

答案 1 :(得分:0)

如果列名相同,则可以使用别名。

SELECT 
p.column1 as p_column1, 
p.product_name as p_product_name , 
s.product_name as s_product_name
FROM products p INNER JOIN suppliers s

有关更多信息:http://www.mysqltutorial.org/mysql-alias/