I'm having a trouble on how can I add a column before column1
which is ID
primary key autoincrement in Navicat sql query.The expected output should automatically increment the number based on the total number selected query
Current data
column1 column2 column3
sample sample sample2
sample sample3 sample4
I want to add primary key column autoincrement before column1 which is id using select query based on number of data from the other column.
expected output
id column1 column2 column3
1 sample sample sample2
2 sample sample4 sample5
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
*What I've tried *
First
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
Second
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
But it seems the result is not the expected result, Is there anyway how to do it? thanks in advance
Your "second" is close to the solution. You missed 3 points:
The solution may be:
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. Think - do you really need in LEFT joining? maybe INNER is enough?