如何更改从其他数据库表中读取数字的条件?

时间:2019-06-14 09:40:40

标签: mysql select

我想用id中的users_tb更改数字2。我该如何补充,users_tb与其他表没有关系,它只是每次在某些活动上更新的一个列ID

SELECT messages.message,messages.sent_date, receiver_user.username, sender_user.username  FROM messages
        INNER JOIN users AS sender_user ON messages.msg_fk_user_id = sender_user.id
        INNER JOIN users AS receiver_user ON messages.receiver_id = receiver_user.id
        WHERE msg_fk_user_id = 1 AND receiver_id = 2 OR msg_fk_user_id = 2 AND receiver_id = 1
        ORDER BY `sent_date`;

1 个答案:

答案 0 :(得分:0)

尝试使用CROSS JOIN

SELECT messages.message,
       messages.sent_date, 
       receiver_user.username, 
       sender_user.username  
FROM messages
INNER JOIN users AS sender_user ON messages.msg_fk_user_id = sender_user.id
INNER JOIN users AS receiver_user ON messages.receiver_id = receiver_user.id
CROSS JOIN users_tb
WHERE msg_fk_user_id = 1 
AND receiver_id = users_tb.id
OR msg_fk_user_id = users_tb.id 
AND receiver_id = 1
ORDER BY `sent_date`
  

交叉联接返回行的笛卡尔积   从两个表。与INNER JOIN或LEFT JOIN不同,交叉联接   在连接的表之间不建立关系。 ...在   一般,如果第一个表有n行,第二个表有m行   行,交叉连接将产生n x m行。

我不知道数据库的结构,但是如果您想使用上面的查询,我认为您需要在users_tb表上插入一些过滤器。 或者让我知道您是如何获得 2号的,我将通过改善查询方式来帮助您,例如:

...
CROSS JOIN (SELECT * FROM users_tb ORDER BY id DESC LIMIT 1) as users_tb
...