PHP,mysql会话列表获取聊天记录最后一条以及未读消息条数

需求

项目中用到即时消息,需要查询会话列表

mysql查询会话列表,每条记录包含以下字段:

未读消息条数,

最后一条消息内容

发送时间

朋友id

朋友昵称

 

sql  :

select t.*,m.nickname,m.avatar from
(

SELECT
	sum( read_status ) AS unread,
	receiver,
	type,
	content,
	send_time
FROM
	(
	SELECT
		to_user_id AS receiver,
		type,
		content,
		0 AS read_status,
		send_time 
	FROM
		message 
	WHERE
		 from_user_id = 4 
		AND  to_user_id <> 4 UNION
	SELECT
		from_user_id AS receiver,
		type,
		content,
		read_status,
		send_time 
	FROM
		message 
	WHERE
		 from_user_id <> 4  
		AND  to_user_id = 4 
	ORDER BY
		send_time DESC 
	) AS newTable
GROUP BY
	receiver 
ORDER BY
	send_time DESC 
	LIMIT 30 ) as t INNER JOIN member m ON t.receiver = m.id 

数据表结构

PHP,mysql会话列表获取聊天记录最后一条以及未读消息条数_第1张图片

查询结果

 

PHP代码

 

$sql = "SELECT
	t.*,
	m.nickname,
	m.avatar 
FROM
	(
	SELECT
		sum( read_status ) AS unread,
		receiver,
		type,
		content,
		send_time 
	FROM
		(
		SELECT
			to_user_id AS receiver,
			type,
			content,
			0 AS read_status,
			send_time 
		FROM
			message 
		WHERE
			from_user_id = $userId 
			AND to_user_id <> $userId UNION
		SELECT
			from_user_id AS receiver,
			type,
			content,
			read_status,
			send_time 
		FROM
			message 
		WHERE
			from_user_id <> $userId 
			AND to_user_id = $userId 
		ORDER BY
			send_time DESC 
		) AS newTable 
	GROUP BY
		receiver 
	ORDER BY
		send_time DESC 
		LIMIT 30 
	) AS t
	INNER JOIN member m ON t.receiver = m.id";
        $list = $this->query($sql);

 

效果

 

PHP,mysql会话列表获取聊天记录最后一条以及未读消息条数_第2张图片

你可能感兴趣的:(php,小程序,mysql)