如何从mysql表中选择消息

时间:2018-10-27 08:33:38

标签: mysql

我的mysql表db.users.aggregate([ { $match: { search: "flarize" } }, { $lookup: { from: "users", let: { friendId: "$friend.id" }, pipeline: [ { $match: { $expr: { $in: ["$_id", "$$friendId"] }}}, { $limit: 10 }, { $project: { email: 0, password: 0 }} ], as: "friend" }} ]) from_id中有两个字段

to_id

但这有点不可思议,有没有办法使查询更合理?

就像我想要我已发送的所有邮件以及已发送给我的邮件

1 个答案:

答案 0 :(得分:3)

您可以使用UNION ALL

SELECT * 
FROM `messages` 
WHERE `from_id` = $user1_id AND `to_id` = $user2_id
UNION ALL
SELECT *
FROM `messages`
WHERE `from_id` = $user2_id AND `to_id` = $user1_id;

或者:

SELECT * 
FROM messages
WHERE (`from_id`, `to_id`) IN (($user1_id,$user2_id),($user2_id,$user1_id))