在MySQL请求SELECT中更改参数

时间:2015-01-30 23:17:53

标签: mysql

我正在尝试使用另一个表中的参数更改'from_user'并且它不起作用,但是当我使用相同的表时,它就像魅力一样:

 SELECT from_user, message_contents, message_read, to_user, date 
 FROM table1 
 WHERE date IN ( 
 SELECT MAX( date ) 
 FROM table1 
 WHERE to_user = 1 GROUP BY from_user 
 ) 
 ORDER BY from_user ASC , date DESC

但这个只显示一条记录,但不是最新的记录:

 SELECT table2.`display_name`, message_contents, message_read, to_user, date 
 FROM table1, table2
 WHERE table1.`from_user` = table2.`ID`
 AND date IN ( SELECT MAX( date ) 
 FROM table1
 WHERE to_user = 1 GROUP BY from_user 
 ) 
 ORDER BY from_user ASC , date DESC

有人可以帮助用table2。display_name参数更改'from_user',但要从mySQL获取所有最近的记录吗?

1 个答案:

答案 0 :(得分:1)

您正在table1.from_user = table2.id加入两个表格 因此,如果您不希望表2影响行数,则可以进行如下查询:

SELECT 
     table1.from_user,
     table2.`display_name`, 
     message_contents, 
     message_read, 
     to_user, 
     date 
FROM table1
LEFT JOIN table2 ON table1.`from_user` = table2.`ID`
WHERE 
     date IN (SELECT MAX(date) FROM table1 WHERE to_user = 1 GROUP BY from_user) 
ORDER BY from_user ASC , date DESC

我在select子句中添加了table1.from_user,这将帮助您查看没有显示名称的用户。