Answer the question
In order to leave comments, you need to log in
How to take the minimum id from a particular SQL set?
The Car table is the parent table. The Human table is a child table (the foreign key car_id of the Human table refers to the car_id of the Car table).
The Car table has 2 fields: car_id (int) and model (varchar). Model stores car brands. But these marks are repeated, ie. a car, for example Huinday, can have id 1 and 5. And two people from the Human table in the car_id field can have values 1 and 5. That is, these different people have the same car brand (Huinday), but their car_id is different.
I want this car_id to become single now and there is no confusion. Those. if a person has a Huinday, then only car_id=1 will be in his field. If someone else has Huinday, then he will also have car_id = 1, not 5.
Another example:
There are duplicate cars in the Car table: LADA (2 times) and BMW (3 times).
In the Human table, people with id 3005, 3006, 3007 have the same car brands (car_id = 7,4,1, these are all BMWs).
And they should have a single car_id, i.e. car_id = 1 (this is a BMW) for id=3005,3006,3007.
That is, remove unnecessary car_id from the Car table if this car has already been seen before.
Similarly, people with id = 3002, 3004 with LADA brands. (car_id for LADA = 3 and 6 from the Car table)
After the query is executed, id=3002 car_id should remain 3, and the person with id=3004 should also have car_id = 3, not 6
Query for Microsoft SQL Server subd.
I wrote a query, but it replaces all car_id with one (as minimum)
I wrote a query that should update the Human table, changing the car_id field there to the minimum of its type (well, if it is LADA, then the minimum is from the set 3, 6).
However, it replaces ALL car_id in the Human table with 1:
update Human set car_id = (
select min(car_id) from Car c where c.Model in (
select Model from Car inner join Human on Human.car_id= Car.car_id));
Answer the question
In order to leave comments, you need to log in
UPDATE Human
JOIN Car ON Car.car_id = Human.car_id
JOIN (
SELECT model, MIN(car_id) AS car_id
FROM Car
GROUP BY model
) AS c ON c.model = Car.model
SET Human.car_id = c.car_id
-- Обновление минимальным кодом:
UPDATE Human
SET car_id = UniqCar.min_id
FROM Human
INNER JOIN Car ON Human.car_id = Car.car_id
INNER JOIN (SELECT MIN(car_id) AS min_id, model
FROM Car AS CarMini
GROUP BY model) AS UniqCar ON UniqCar.model = Car.model
-- Удаление лишних машин:
DELETE FROM Car
WHERE Car.car_id <> (SELECT MIN(CarOff.car_id) FROM Car AS CarOff WHERE CarOff.model = Car.model)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question