sql 查询结果横向拼接

2022-05-11 15:21:01

1.纵向拼接 俩个结果即上下堆叠(类比:一个表中相邻的俩行)用union关键字即可
2.横向拼接 俩个结果集左右挨在一起 (类比:一个表中相邻的俩列)
第二种给个 例子 t1,t2 ,是查询同一张表的不同字段产生的俩个结果集(行数相同)
SELECT t1.username, t1.userHePHo, t1.commentid, t1.childcommentid,
t1.userid, t1.content, t1.cre_time,t2.beuserid,t2.beusername FROM

                (SELECT username,userHePHo,commentid,childcommentid,
                c.userid,content,c.cre_time FROM
                 `user` u JOIN childcomment c   ON u.userid=c.userid WHERE goodsid=1) t1,
                 
                (SELECT  commentid,u1.username AS beusername,beuserid FROM `user` u1
                                JOIN childcomment c1 ON
                u1.userid=c1.BeUserId  WHERE goodsid=1) t2
                
    ON t1.commentid=t2.commentid

得到结果 结果是笛卡尔积
(数据库关联字段数据不唯一 如 俩id都是28 将产生笛卡尔积)
解决方法:持久层无法解决 应用层解决,利用list (元素有序且可重复)和set(元素无序且唯一)特性进行去重。

  • 作者:李建之父
  • 原文链接:https://blog.csdn.net/m0_50816499/article/details/124544795
    更新时间:2022-05-11 15:21:01