我正在尝试订购mysql,然后将其分组。这是我的表:
|------
|Column|Type|Null|Default
|------
|//**id**//|int(11)|No|
|consultantid|int(11)|Yes|NULL
|startdate|datetime|Yes|NULL
|enddate|datetime|Yes|NULL
|target|varchar(255)|No|
|dateinserted|datetime|No|CURRENT_TIMESTAMP
== Dumping data for table consultant_targets
|1|1|2016-11-01 00:00:00|2016-11-29 00:00:00|10000|2016-10-31 21:34:55
|2|1|2016-10-31 00:00:00|2016-11-23 00:00:00|15000|2016-10-31 22:03:09
第二条记录的插入时间晚于第一条记录,这就是我想要得到的 - 所以如果有50条记录,它就会抓住最新记录。这是我的SQL:
SELECT
*
FROM
(
SELECT
ct.*,
u.username,
u.colorcode
FROM
consultant_targets ct
INNER JOIN user u ON u.id = ct.consultantid
ORDER BY
dateinserted desc
) AS ctu
GROUP BY
consultantid
但我每次只获得第一行,具有10000目标的那一行
答案 0 :(得分:1)
您可以使用NOT EXISTS()
:
SELECT t.*,
u.username,
u.colorcode
FROM consultant_targets t
INNER JOIN user u
ON u.id = t.consultantid
WHERE NOT EXISTS(SELECT 1 FROM consultant_targets s
WHERE t.consultantid = s.consultantid
AND s.dateinsereted > t.dateinsereted)