获取新插入元素或现有元素的最后一个ID

时间:2016-12-24 10:52:49

标签: mysql

我有一个以下地图表,名称列上有一个唯一键:

id | name
1    aaa
2    bbb
3    ccc

如果我向此表插入一个新值,我想获得一个新创建的ID,如下所示:

INSERT IGNORE INTO map VALUES(null, 'ddd');

我知道我可以使用getLastId()函数执行此操作。但是如果名称已经存在,我也想获取ID,getLastId()函数在这种情况下返回0:

INSERT IGNORE INTO map VALUES(null, 'ccc');

这可能与一个SQL有关,而不检查是否存在记录等?

2 个答案:

答案 0 :(得分:1)

我认为你需要加倍努力:

  • 检查是否存在 - 何时:获取该名称的ID
  • 如果不是:SELECT DISTINCT Month,MonthName,Year INTO #dates FROM Calendar WHERE DATE >= @StartDate AND DATE < DATEADD (d,1,@EndDate) CREATE UNIQUE CLUSTERED INDEX uq0_#dates ON #dates (Month,Year) SELECT A.StageName, C.Month, C.MonthName as Label, C.Year, isnull(A.Average,0) as Data FROM ( SELECT S.StageName, MonthNumber, Year, Average FROM ( SELECT VM.StageID, MONTH(TimeIn) as MonthNumber, YEAR(TimeIn) as Year, ISNULL(AVG(DATEDIFF(mi,TimeIn,isnull(TimeOut,@TodayDate))),0) as Average FROM VisitMovement VM WHERE (VM.TimeIn >= @StartDate AND VM.TimeIn < DATEADD (d,1,@EndDate)) AND (VM.TimeOut < DATEADD (d,1,@EndDate) OR VM.TimeOut IS NULL) GROUP BY VM.StageID, MONTH(TimeIn), YEAR(TimeIn) ) grp JOIN Stage S ON S.StageID = grp.StageID ) ) A RIGHT OUTER JOIN #dates C on A.MonthNumber = C.Month and -- A.Month = C.MonthName and A.Year = C.Year ORDER BY CASE WHEN @Ordering = 'asc' THEN C.Year END ASC, CASE WHEN @Ordering = 'asc' THEN C.Month END ASC, CASE WHEN @Ordering = 'asc' THEN A.StageName END ASC, CASE WHEN @Ordering = 'desc' THEN C.Year END DESC, CASE WHEN @Ordering = 'desc' THEN C.Month END DESC, CASE WHEN @Ordering = 'desc' THEN A.StageName END DESC

答案 1 :(得分:1)

取决于哪种资格作为单一查询。

当您使用LAST_INSERT_ID()时,您可以控制INSERT INTO map (name) VALUE ('ccc') ON DUPLICATE KEY UPDATE id = LAST_INSERT_ID(id); ,使其在插入时返回新ID,并在更新时“更新”行的ID:

LAST_INSERT_ID()

这将使map.id然后返回您感兴趣的行的getLastId()

无论您将API命名为SELECT LAST_INSERT_ID(); (我不知道它,因此我无法提供更多指针)这可能不起作用,然后您需要触发第二个查询到获得它:

>>> chr(ord("一") + 1)
    '丁'

参见: