在SQL語句select中根据某个字段值,修改另外一个查询出来字段的值

消息表:

CREATE TABLE `z_message` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT ‘消息ID’,
  `send_type` tinyint(1) NOT NULL DEFAULT ‘0’ COMMENT ‘发送类型 1手动 2自动’,
  `type` tinyint(1) NOT NULL DEFAULT ‘0’ COMMENT ‘消息分类 1全站 2男性 3女性 4个人’,
  `user_id` int(11) NOT NULL DEFAULT ‘0’ COMMENT ‘用户id 0全站’,
  `title` varchar(255) NOT NULL COMMENT ‘标题’,
  `content` varchar(1000) NOT NULL COMMENT ‘内容’,
  `status` tinyint(1) DEFAULT ‘0’ COMMENT ‘状态 0未读 1已读 2删除’,
  `is_enable` bit(1) DEFAULT b’1′ COMMENT ‘是否有效’,
  `is_delete` bit(1) DEFAULT b’0′ COMMENT ‘是否删除’,
  `add_time` int(12) DEFAULT NULL COMMENT ‘记录添加时间’,
  `update_time` int(12) DEFAULT NULL COMMENT ‘最近一次修改时间’,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=MyISAM AUTO_INCREMENT=213 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC COMMENT=’系统消息’;

已读表:

CREATE TABLE `z_message_read` (
  `user_id` int(11) NOT NULL COMMENT ‘用户ID’,
  `message_id` int(11) NOT NULL COMMENT ‘消息ID’,
  UNIQUE KEY `READ_PRIMARY_KEY` (`message_id`,`user_id`) USING BTREE
) ENGINE=MyISAM DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;

删除表:

CREATE TABLE `z_message_del` (
  `user_id` int(11) NOT NULL COMMENT ‘用户ID’,
  `message_id` int(11) NOT NULL COMMENT ‘消息ID’,
  UNIQUE KEY `DEL_PRIMARY_KEY` (`message_id`,`user_id`) USING BTREE
) ENGINE=MyISAM DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;

需求:查询未被删除的消息,并标记消息已读和未读

sql语句:

SELECT 
`z_message`.`id`, `z_message`.`title`, `z_message`. `content`
— , `z_message`. `status`
— , `z_message_read`.`message_id` AS `read_id`
— , `z_message_del`.`message_id` AS `del_id`
, CASE WHEN `z_message_read`.`message_id` > 0 THEN 1 ELSE `z_message`.`status` END `status`
FROM `z_message` 
LEFT JOIN `z_message_del` ON `z_message`.`user_id` = `z_message_del`.`user_id` 
LEFT JOIN `z_message_read` ON `z_message`.`user_id` = `z_message_read`.`user_id`
WHERE `z_message_del`.`user_id` IS NULL 
AND (`z_message`.`type` = 1 OR `z_message`.`type` = 3 OR `z_message`.`user_id` = 164)
;

    原文作者:drzdryse
    原文地址: https://blog.csdn.net/m0_37711659/article/details/108166102
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞