个人技术--联表查询
这个作业属于哪个课程 2021软件工程实践
这个作业要求在哪里 软件工程实践个人总结&个人技术
这个作业的目标 个人技术总结、分享
其他参考文献 微信官方文档

技术概述

  • 微信小程序联表查询问题,在数据库中有两张表,需要联合两张表查询内容,通过某一键值链接。sql语句如下:Select 列名 [[,列名]...] from 表名1,表名2,,... Where 查询条件;

  • 比如数据库中有这样两张表

    • user表

      userId: ‘用户唯一标识’
      userPic: ‘用户头像’
      userName ‘用户名’
    • comment表:

      _Id ‘评论唯一标识’
      content ‘评论内容’
      userId ‘用户标识’
      createTime ‘评论时间’
      postid ‘文章唯一标识’

现在要读出每一条评论的内容、发布时间、用户名及用户头像,则需联表查询。

技术详述

  1. 表最麻烦的办法就是先查出一个表的内容,再用循环+判断去查询第二个表存入第一个表查询内容数组中,如下:

    //取出所有评论
    await db.collection('comment')
        .where({
            postid: id,
        })
        .get()
        .then(res=>{
            commentList =  res.data
         })
         console.log(commentList);
    //取出每条评论中的userid查询user表
    for( var i= 0; i < commentList.length; i++ ){
          await db.collection('user')
          .where({
              userid: commentList[i].userid,
          })
          .get()
          .then(res=>{
          //取出每条评论的用户名及头像
            userPic[i] =  res.data[0].userPic
            userName[i] =  res.data[0].userName
           })
      }
      //最后再整合commentList、userPic、userName数组
    
  2. 上述方法简单易懂,但是比较麻烦,在小程序中使用lookup解决联表查询,上例代码如下:

    const db = cloud.database()
    db.collection('comment').aggregate()
      .lookup({
        from: 'user',   //要联合的另一张表
        localField: 'userId',  //输入记录的要进行相等匹配的字段
        foreignField: 'userId', //被连接集合的要进行相等匹配的字段
        as: 'commentUser', //输出的数组字段名
      })
      .end()
      .then(res => console.log(res))
      .catch(err => console.error(err))
    
    

    输出结果格式如下:

    [
    	{
    		"_id":
    		"content":
    		"userId":
    		"createTime":
    		"postId":
    		"commentUser":[
    			{
    				"userId":
    				"userPic":
    				"userName":
    			}
    		]
    	},
    	...
    ]
    
  3. 如果想要的输出格式是将user信息直接合并到comment中,则可使用如下方法:

    var db = cloud.database()
    var $ = db.command.aggregate
    db.collection('comment').aggregate()
      .lookup({
        from: "user",
        localField: "userId",
        foreignField: "userId",
        as: "commentUser"
      })
      .replaceRoot({
        newRoot: $.mergeObjects([ $.arrayElemAt(['$commentUser', 0]), '$$ROOT' ])
      })
      .project({
        commentUser: 0
      })
      .end()
      .then()
      .catch(err => console.error(err))
    
    

    输出格式如下:

    [
    	{
    		"_id":
    		"content":
    		"userId":
    		"createTime":
    		"postId":	
    		"userPic":
    		"userName":
    	},
    	...
    ]
    

总结

  1. 使用最简单粗暴的方法联表查询,借助数组,易懂。
  2. 使用lookup联表查询。
  3. 整合结果使用mergeObjects合并对象。

参考文档

微信官方文档

posted on 2021-06-28 11:51  zzong  阅读(141)  评论(0编辑  收藏  举报