php - 在多列mysql子查询中获取最高ID

标签 php mysql sql database

<分区>

这是我得到的表:

id   userid  contactid
401     7   1
403     7   1
405     3   7
407     1   7
408     7   1
409     7   3 
410     3   7
411     7   1 
412     7   3 
413     7   4 
420     1   7 
423     7   1

我想从中得到的是userid或contactid的最高id为7时

SELECT id from table WHERE userid=7 OR contactid=7 
AND id NOT IN 
(SELECT id from table WHERE userid=7 OR contactid=7 
ORDER BY id DESC LIMIT 1)

这就是我所做的,但没有用。

在此查询中,我想接收 3 行,它们是:(id) 412,413,423

谢谢!

最佳答案

嗯,Colandus 的解释有点道理:

select userid, contactid, max(id)
from t
where userid = 7
group by userid, contactid;

但是,如果我将这些视为没有顺序的成对,那么这个版本对我来说最有意义:

select least(userid, contactid), greatest(userid, contactid), max(id)
from t
where userid = 7 or contactid = 7
group by least(userid, contactid), greatest(userid, contactid)

当我以这种方式思考问题时,问题开始真正有意义了。

关于php - 在多列mysql子查询中获取最高ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16754806/

相关文章:

javascript - DataTables(jQuery 的表格插件)在导航离开和返回 DataTable 时从上次中断的地方继续

sql - 设置外键时的奇怪问题

mysql 查询需要 13 分钟才能运行

php短网址奇怪的外观

php - 互连服务的 ZF3 服务 DI 的有效模式

mysql - 条件不起作用的地方

mysql - 如何在 JDBCTemplate 中使用 like 语句检索列表?

mysql 排名变量

php - 在 xampp 中找不到对象

mysql - 每个查询都会创建一个新的 CONNECTION_ID()