查询增量数Mysql主键

Query incremental number Mysql Primary Key

我遇到了一个问题,如何在 column1 之前添加一列,这是 Navicat 中的 ID 主键自动增量 sql query.The 预期输出应该自动根据 selected 查询

的总数递增数字

当前数据

 column1    column2    column3

 sample    sample     sample2
 sample    sample3    sample4

我想在 column1 之前添加主键列自动增量,它是 id 使用 select 查询基于来自另一列的数据数。

预期输出

 id    column1   column2  column3
  1    sample   sample   sample2
  2    sample   sample4  sample5

Image

SELECT  sc.id as b2_id,app.covid_id,app.payroll_batch,app.paid_by,app.date_receive,app.remarks,app.eligible,app.amount,app.amount_paid,app.amount_unpaid  
FROM `app_person` as app 
LEFT JOIN b2_sac_numbers AS sc ON sc.sac_number = app.covid_id 

*我试过的*

第一个

SELECT (SELECT COUNT(id) +1) as id, 
       sc.id as b2_id,app.covid_id,app.payroll_batch,app.paid_by,app.date_receive,app.remarks,app.eligible,app.amount,app.amount_paid,app.amount_unpaid  
FROM `app_person` as app 
LEFT JOIN b2_sac_numbers AS sc ON sc.sac_number = app.covid_id 

第二

SELECT @rownum :=@rownum+1 as id, 
       sc.id as b2_id,app.covid_id,app.payroll_batch,app.paid_by,app.date_receive,app.remarks,app.eligible,app.amount,app.amount_paid,app.amount_unpaid  
FROM `app_person` as app 
LEFT JOIN b2_sac_numbers AS sc ON sc.sac_number = app.covid_id 

但是好像不是预期的结果,请问有什么办法吗?提前致谢

您的“第二个”接近解决方案。您错过了 3 分:

  1. 变量未初始化
  2. 没有行排序 (ORDER BY)
  3. 此类枚举查询的行源只能使用一个table

解决方案可能是:

SELECT @rownum := @rownum+1 as id, 
       b2_id, covid_id, payroll_batch, paid_by, date_receive, 
       remarks, eligible, amount, amount_paid, amount_unpaid
FROM ( SELECT sc.id as b2_id, app.covid_id, app.payroll_batch, app.paid_by,
              app.date_receive, app.remarks, app.eligible, app.amount, 
              app.amount_paid, app.amount_unpaid  
       FROM `app_person` as app 
       LEFT JOIN b2_sac_numbers AS sc ON sc.sac_number = app.covid_id ) AS total_data
CROSS JOIN (SELECT @rownum := 0) init_variable
ORDER BY {some expression of columns which provides rows uniqueness}

PS。想想——你真的需要在 LEFT 中加入吗?也许 INNER 就足够了?