Eliminate rows with duplicate values ​​in column a from a table
P粉366946380
P粉366946380 2024-03-31 10:42:26
0
1
382

Is there a way to check if lead_id appears multiple times in the table and if so, exclude it from the query? The reason is that I only want to add a new row if status_id = 1 and no other status_id/row for that Lead_id is found.

The database is designed in such a way that every status update creates a new row. Therefore, old rows have older timestamps and remain in the database table, and these will be displayed in the status history component of the frontend. But since it is designed this way, I can't simply say: give each user a status 1 and a new status update. Because then it will add a row for each Lead_id since all leads will enter the database with status_id 1.

Queries I've used so far:

INSERT INTO `lead_has_status` (`lead_id`, `lead__status_id`, `comment`, `created_at`, `updated_at`)
SELECT (`lead_id`, 13, "", `created_at`, `updated_at`)
WHERE `lead__status_id` = 1 AND 

What does the data look like:

lead_id status_id More data
1 1 data
1 12 data
2 1 data
2 14 data
3 1 data
4 1 data
5 1 data
6 1 data

For each new lead (form submission), it will create a row and give that lead status_id 1 (status: new). I do need to batch update the 200+ leads from 1 to another status_id, but with the query I have now, it will update every row that contains a status_id of 1. What I want is that it will first check if the Lead_id exists in the table only once and if true then add a new row with the updated status_id.

So after the sql query it needs to look like this:

lead_id status_id More data
1 1 data
1 12 data
2 1 data
2 14 data
3 1 data
3 12 data
4 1 data
4 12 data
5 1 data
5 12 data
6 1 data
6 12 data

TLDR: If Lead_id is found only once in the table, add a new row with status_id.

P粉366946380
P粉366946380

reply all(1)
P粉441076405

If each row of your table has a unique ID, then you can use a query like this

INSERT INTO `lead_has_status` (`lead_id`, `lead__status_id`, `comment`, `created_at`, `updated_at`)
SELECT (`lead_id`, 13, "", `created_at`, `updated_at`)
FROM `lead_has_status` l
WHERE `lead__status_id` = 1 AND NOT EXISTS ( 
  SELECT 1 FROM lead_has_status 
  WHERE `lead_id` = l.`lead_id` AND id  l.id );

and no ID

INSERT INTO `lead_has_status` (`lead_id`, `lead__status_id`, `comment`, `created_at`, `updated_at`)
SELECT (`lead_id`, 13, "", `created_at`, `updated_at`)
FROM `lead_has_status` l
WHERE `lead__status_id` = 1 AND  () 
  SELECT COUNT(*) FROM lead_has_status 
  WHERE `lead_id` = l.`lead_id`) = 1 ;
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template