[英]Select data from table using SQL query
I have a table name "chat_details" I wanna access only data with green underline according to time, I use the following query我有一个表名“chat_details”我只想根据时间访问带有绿色下划线的数据,我使用以下查询
//suppose $user_id = 1;
"SELECT *
FROM chat_details WHERE from_user_id='$user_id' OR to_user_id='$user_id' ORDER BY time DESC"
It fetch all the rows because all rows contain user_id = 1 in one of the column, but i need only green underline rows as compare to red one because green one are latest according to time(column), how can i fetch only these green underlines?它获取所有行,因为所有行在其中一列中都包含 user_id = 1,但我只需要绿色下划线行与红色行相比,因为绿色行根据时间(列)是最新的,我怎么能只获取这些绿色下划线?
This is one posible query, that should solve your question.这是一个可能的查询,应该可以解决您的问题。
SELECT *
FROM chat_details c
WHERE (c.from_user_id='$user_id' OR c.to_user_id='$user_id')
AND NOT EXISTS (
SELECT 1 FROM chat_details d
WHERE d.from_user_id = c.from_user_id
AND d.to_user_id = c.to_user_id
AND d.time > c.time)
ORDER BY c.time DESC"
Actually I could not test, hope I haven't made a mistake.实际上我无法测试,希望我没有弄错。
The query selects all data as in your query, but only thoose which haven't a newer chat between the two users.该查询选择您的查询中的所有数据,但仅选择两个用户之间没有较新聊天的数据。 For the EXISTS keyword see http://www.mysqltutorial.org/mysql-exists/
对于 EXISTS 关键字,请参阅http://www.mysqltutorial.org/mysql-exists/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.