简体   繁体   English

如何在MySQL中的2条记录中选择最后一个日期

[英]How to select last date in 2 record in Mysql

How to select last date in 2 records in Mysql ? 如何在Mysql的2条记录中选择最后日期?

TABLE A 表A

SID NAME Sex
1  Jam  M
2  Da   F

TABLE B 表B

 ID Title SID Date
   1  A     1   2012-07-31 09:57:10
   2  NULL  1   2012-07-31 09:57:13
   3  A     2   2012-07-31 10:10:13
   4  NULL  2   2012-07-31 10:57:13

I want to inner join those two tables, 我想内部连接这两个表,

but select only one record only of Table B(distinct of SID) where title not null then show the 但仅选择表B(SID的不同)的一条记录,其中标题不为null,然后显示

biggest Date of title is null field. 最大标题日期为空字段。

Result want the biggest Date of Null title: 结果想要最大的Null日期标题:

ID Name Title SID  Date
1  Jam  A     1    **2012-07-31 09:57:13**
2  DA   A     2    **2012-07-31 10:57:13**

How to do that ? 怎么做 ?

I think something like this will work for you: 我觉得这样的事情会为你工作:

SELECT b.ID, a.NAME, b.Title, b.SID, b.Date
FROM TABLEA a
    INNER JOIN (SELECT SID, IFNULL(Title, "") AS Title,
                       MAX(IF(Title IS NULL, Date, NULL)) Date
                FROM TABLEB GROUP BY SID) b
        ON a.SID = b,SID;
SELECT b.ID, a.NAME, b.Title, b.SID, b.Datea 
from tablea a left outer join 
  (( SELECT sid, MAX(datea) AS latest
         FROM tableb
          where title is not null 
          GROUP BY sid) AS dt
INNER JOIN tableb b  ON b.sid= dt.sid  and b.datea=dt.latest )
on a.sid=b.sid

Try my code (it works): 试试我的代码(它可以工作):

SELECT b.id, b.title, b.sid, b.date 
    FROM table_b as b 
    JOIN table_a as a ON a.sid = b.sid
    WHERE b.id in (SELECT MAX(id) FROM table_b GROUP BY sid)

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

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