简体   繁体   English

选择VARCHAR列的最大值-MySQL

[英]Select max value for a VARCHAR column - MySQL

My table for message inbox concept email is a primary in the table. 我的邮件收件箱概念电子邮件表格是该表格中的主要表格。 I want to get the last message which is sent by particular email. 我想获取由特定电子邮件发送的最后一条消息。

tbl_msg: tbl_msg:

id
email
msg

Example Data: 示例数据:

Id  email            msg
1   xyz@gmail.com    This is test    
2   abc@gmail.com    All is well
3   xyz@gmail.com    This is test2

I want to get the last appearance of each email and msg 我想获取每封电子邮件和味精的最新外观

Id  email            msg

2   abc@gmail.com    All is well
3   xyz@gmail.com    This is test2

What I tried: 我试过的

SELECT cnote.`id`,cnote.`email`,cnote.`msg` FROM `tbl_msg` cnote inner join (select distinct email,id from client_com group by email) as note
on cnote.id=note.id

Guide me if I wrong 指导我如果我错了

To get the latest messsage for each email address in the table you do not need a JOIN , you just need to ORDER and GROUP BY : 要获取表中每个电子邮件地址的最新消息您不需要JOIN ,只需执行ORDERGROUP BY

SELECT `id`, `email`, `msg`
FROM `tbl_msg`
GROUP BY `email`
ORDER BY `id` DESC

Use This query: 使用此查询:

SELECT m1.* FROM tbl_msgs m1 LEFT JOIN tbl_msgs m2  ON (m1.email = m2.email AND m1.id < m2.id) WHERE m2.id IS NULL;

This will join with the same table and with condition m1.id < m2.id , will get the latest one. 这将与同一张表连接,条件为m1.id < m2.id ,将获得最新的表。

Another option is using subquery: 另一种选择是使用子查询:

SELECT * FROM tbl_msgs WHERE id IN (SELECT MAX(id) FROM tbl_msgs GROUP BY email);

You can use this query: 您可以使用以下查询:

SELECT id, email, msg FROM you_table 
GROUP BY email
ORDER BY id DESC

With this one you will have only 1 row per email, and you'll have the last because is ordered by id DESC. 有了这个,您每封电子邮件将只有1行,并且由于ID DESC的排序,您将拥有最后一行。

If you are running a PDO connection (The way I know to do it, not sure if there is a MySQLi way) 如果您正在运行PDO连接(我知道的连接方式,不确定是否有MySQLi方式)

$theLastIdGiven = $handlerDbConnection->lastInsertId();

Or if you want to run it through a query, and get the last result, just add ORDER BY id DESC LIMIT 0, 1 and that will order the data by id in a descending form then get the first bit of data :) 或者,如果您想通过查询运行它并获得最后的结果,只需添加ORDER BY id DESC LIMIT 0, 1它将按id降序排列数据,然后获取数据的第一位:)

Hope this helped you! 希望这对您有所帮助!

选择ID,电子邮件,来自tbl_msg的消息在哪里输入ID((从tbl_msg GROUP BY电子邮件中选择MAX(ID))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM