左外连接

优质
小牛编辑
136浏览
2023-12-01

LEFT OUTER JOIN 左外连接

  • [ ] 需求:查询所有分类,如果该分类下没有商品,则不显示该分类
  • [ ] 实现:
    
    SELECT 
      `goods`.`id`, 
      `goods`.`title`, 
      `goods`.`price`, 
      `goods`.`cate_id`, 
      `cate`.`id`, 
      `cate`, 
      `cate.title` 
          FROM 
              `goods` 
          LEFT OUTER JOIN 
              `category` AS `cate` 
          ON 
              `goods`.`cate_id` = `cate`.`id`;

const cate = await this.ctx.model.Category.findAll({ include: [{ model: this.ctx.model.Goods, as: 'goods', attributes:['title', 'price'], // 实现 左外连接 required: true, }], distinct: true });