我正在制作一个类似于 tindler 的约会应用程序,用户可以在其中互相喜欢或不喜欢对方。如果两个用户都喜欢对方,他们应该能够互相聊天。我提出了以下查询来处理拉出您可以聊天/已经聊天的用户列表 - 我遇到的问题是我只想拉出最近的聊天消息,只是为了在你面前显示一点信息点击进入聊天本身。我的查询有效,但它返回最旧(最低 ID)的聊天记录,而不是最新的。Order by 似乎对返回正确结果没有影响。
$data = $this->db->select('users.id,display_name,city,state,gender,users_pictures.picture,users_chats.message')
->join('users_pictures','users_pictures.user_id=users.id')
->join('users_chats','users_chats.user_id=users.id OR users_chats.foreign_user_id=users.id','left outer')
->where('EXISTS (SELECT 1 FROM users_likes_dislikes ld WHERE (ld.foreign_user_id = '.$this->user_id.' AND ld.user_id=users.id AND ld.event_type=1) OR (SELECT 1 FROM users_likes_dislikes ld WHERE ld.foreign_user_id = users.id AND ld.user_id='.$this->user_id.' AND ld.event_type=1))', '', FALSE)
->where('NOT EXISTS (SELECT 1 FROM users_blocks ub WHERE (ub.foreign_user_id = users.id AND ub.user_id='.$this->user_id.') OR (SELECT 1 FROM users_blocks ub WHERE ub.foreign_user_id = '.$this->user_id.' AND ub.user_id=users.id))', '', FALSE)
->where('((users_chats.user_id='.$this->user_id.' OR users_chats.foreign_user_id='.$this->user_id.') OR (users_chats.user_id is NULL AND users_chats.foreign_user_id is NULL))')
->order_by('users_chats.id','DESC')
->group_by('users.id')
->get('users')
->result_array();
这是 users_chats 的当前 mysql 表:
id user_id foreign_user_id message created
1 1 4 test 2013-05-22 15:42:44
2 1 4 test2 2013-05-22 15:44:38
我假设 order_by 将确保 test2 消息是显示的内容。
这是示例输出:
Array ( [0] => Array ( [id] => 4 [display_name] => testinguser [city] => west hills [state] => ca [gender] => 2 [picture] => testasdfasdf.jpg [message] => test ) )
任何帮助深表感谢 :)
编辑 - 查询本身(没有分组依据,这有效,但我需要将它分组到 user.id 以便我在数组中没有同一用户的多个条目):
SELECT
`users`.`id`,
`display_name`,
`city`,
`state`,
`gender`,
`users_pictures`.`picture`,
`users_chats`.`message`
FROM (`users`)
JOIN `users_pictures`
ON `users_pictures`.`user_id` = `users`.`id`
JOIN `users_chats`
ON `users_chats`.`user_id` = `users`.`id`
OR users_chats.foreign_user_id = users.id
WHERE EXISTS(SELECT
1
FROM users_likes_dislikes ld
WHERE (ld.foreign_user_id = 1
AND ld.user_id = users.id
AND ld.event_type = 1)
OR (SELECT
1
FROM users_likes_dislikes ld
WHERE ld.foreign_user_id = users.id
AND ld.user_id = 1
AND ld.event_type = 1))
AND NOT EXISTS(SELECT
1
FROM users_blocks ub
WHERE (ub.foreign_user_id = users.id
AND ub.user_id = 1)
OR (SELECT
1
FROM users_blocks ub
WHERE ub.foreign_user_id = 1
AND ub.user_id = users.id))
AND ((users_chats.user_id = 1
OR users_chats.foreign_user_id = 1)
OR (users_chats.user_id is NULL
AND users_chats.foreign_user_id is NULL))
ORDER BY `users_chats`.`created` DESC