Dies ist das richtig normalisiert Modell ist:
create table users (
user_id serial primary key,
user_name varchar(100)
);
create table town (
town_id serial primary key,
town_int int
);
create table user_town (
town_id int references town (town_id),
user_id int references users (user_id),
primary key (user_id, town_id)
);
insert into users (user_name) values ('John');
insert into town (town_int) values (1),(2),(3),(4),(5),(6);
insert into user_town (user_id, town_id) values (1,1),(1,2),(1,3),(1,4),(1,5),(1,6);
Wie es abfragen:
select user_id, user_name, town_id, town_int
from
user_town
inner join
users using (user_id)
inner join
town using (town_id)
where user_id = 1
order by town_int desc
limit 2
;
user_id | user_name | town_id | town_int
---------+-----------+---------+----------
1 | John | 6 | 6
1 | John | 5 | 5
Mit einem ordnungsgemäß normalisierten Modell wäre dies einfach. Warum speichern Sie diese Informationen in mehreren Spalten? Warum bringst du das nicht in eine richtige 1: Viele-Beziehung –