热门标签 | HotTags
当前位置:  开发笔记 > 数据库 > 正文

mysql全连接查询合并字段

1、创建两张表t1如下:idname1a13a3t2如下:idname1b12b25b5联合查询合并字段:sql语句:SELECTt3.`name`ASB,t3.`name1`ASC,COALESCE(t3.id2,t3.id1)ASmyIdFROM(SELECTt1.idasid2,t1.`name`asname,t2.idasid1,t2.`na

1、创建两张表 t1如下: id name 1 a1 3 a3 t2如下: id name 1 b1 2 b2 5 b5 联合查询合并字段: sql语句: SELECT t3.`name` AS B, t3.`name1` AS C ,COALESCE(t3.id2,t3.id1) AS myId FROM (SELECT t1.id as id2 ,t1.`name` as name,t2.id as id1 ,t2.`na

1、创建两张表

t1如下:

id name
1 a1
3 a3


t2如下:

id name
1 b1
2 b2
5 b5


联合查询合并字段:

sql语句:

SELECT t3.`name` AS B, t3.`name1` AS C ,COALESCE(t3.id2,t3.id1) AS myId

FROM (SELECT t1.id as id2 ,t1.`name` as name,t2.id as id1 ,t2.`name` as name1 FROM t1 LEFT JOIN t2 on t1.id=t2.id

UNION SELECT t1.id as id2 ,t1.`name` as name,t2.id as id1 ,t2.`name` as name1 from t1 RIGHT JOIN t2 on t1.id=t2.id) as t3 GROUP BY myId;

查询结果:


B C myID
a1 b1 1
b2 2
a3 3
b5 5

推荐阅读
author-avatar
shangce
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有