查询A表数据根据B表过滤某些记录

分类:MySQL     发布时间:2018-05-20     最后更新:2018-12-10     浏览数:1757

最近在做一个审批的项目,需求如下: 某个用户申请加入某一俱乐部,待俱乐部管理员审核过后才算正式加入该俱乐部。 审核记录表结构

CREATE TABLE `ClubMembers` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `user_id` int(11) unsigned NOT NULL,
  `club_id` int(11) unsigned NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

用户和俱乐部关系表结构

CREATE TABLE `JoinClubLogs` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `user_id` int(11) unsigned NOT NULL COMMENT '用户id',
  `action` int(11) unsigned NOT NULL COMMENT '动作,1:申请加入;2:部长拒绝;3:部长允许;4:用户退出俱乐部',
  `club_id` int(11) unsigned NOT NULL COMMENT '俱乐部id',
  `created_at` int(11) unsigned NOT NULL COMMENT '申请时间或者处理时间',
  `handler_id` int(10) unsigned DEFAULT NULL COMMENT '处理人id,俱乐部负责人id',
  `remark` varchar(255) DEFAULT NULL COMMENT '备注',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

当 action 为3时,向 ClubMembers 表插入一条记录,表明用户已经正式加入俱乐部。 那么查询待审批记录应该怎样写?比如 A 俱乐部有多少人是在申请加入俱乐部的?

const joinLogs = await mysql.select('l.id', 'l.user_id as userId', 'l.club_id as clubId', 'c.name as clubName', 'u.name as userName')
    .from('JoinClubLogs as l')
    .innerJoin('Clubs as c', 'l.club_id', 'c.id')
    .innerJoin('Users as u', 'l.user_id', 'u.id')
    .joinRaw('left join (select distinct m.user_id, m.club_id, 1 as test_column from ClubMembers as m) as ll on (l.user_id = ll.user_id AND l.club_id = ll.club_id)')
    .where('l.action', 1)
    .whereNull('ll.test_column')
    .orderBy('l.created_at', 'desc');

以上是基于 knex 库写的查询语句,

knex 是一个SQL查询构建器

上一篇: 开启本机 ssh 客户端 下一篇: Node.js 你知多少?