Postgresql:仅当两个字段分别唯一时才选择字段
我需要选择10个独特的位置,每个位置应该来自不同的用户。 因此,user_id和location_id中的值应该是唯一的。 尝试了很多方法,但不知怎么的,都没有成功 不考虑uniques的查询如下所示:Postgresql:仅当两个字段分别唯一时才选择字段,postgresql,Postgresql,我需要选择10个独特的位置,每个位置应该来自不同的用户。 因此,user_id和location_id中的值应该是唯一的。 尝试了很多方法,但不知怎么的,都没有成功 不考虑uniques的查询如下所示: SELECT b.user_id, l.location_id, ROUND(distance(transform(PointFromText('POINT(4.0 52.0)', 4326), 26986),transform("spatialPoint", 2698
SELECT
b.user_id,
l.location_id,
ROUND(distance(transform(PointFromText('POINT(4.0 52.0)', 4326), 26986),transform("spatialPoint", 26986))) AS distance
FROM locations AS l
JOIN b_user_location AS b USING(location_id)
ORDER BY ROUND(distance(transform(PointFromText('POINT(4.0 52.0)', 4326) ASC
LIMIT 10 OFFSET 0
看来我需要这样的东西:
SELECT
DISTINCT ON(user_id)
DISTINCT ON(location_id)
b.user_id,
.....
SELECT DISTINCT ON(location_id) *
FROM (
SELECT DISTINCT ON(b.user_id)
b.user_id,
l.location_id,
ROUND(distance(transform(PointFromText('POINT(4.0 52.0)', 4326), 26986),transform("spatialPoint", 26986))) AS distance
FROM locations AS l
JOIN b_user_location AS b USING(location_id)
ORDER BY ROUND(distance(transform(PointFromText('POINT(4.0 52.0)', 4326) ASC
)
LIMIT 10 OFFSET 0
但这是不允许的
谁能给我指一下正确的方向吗
[编辑]
链接到SqlFiddle
Sql查询:
CREATE TABLE users (user_id SERIAL, username VARCHAR(255), CONSTRAINT users_pkey PRIMARY KEY (user_id));
CREATE TABLE locations(location_id SERIAL, "spatialPoint" INT,name VARCHAR(255),CONSTRAINT locations_pkey PRIMARY KEY (location_id));
CREATE TABLE b_user_location(user_id INT, location_id INT, CONSTRAINT user_id_fkey FOREIGN KEY(user_id) REFERENCES users(user_id),CONSTRAINT location_id_fkey FOREIGN KEY(location_id) REFERENCES locations(location_id));
INSERT INTO users(username)VALUES('user_1'),('user_2'),('user_3');
INSERT INTO locations("spatialPoint", name)VALUES(1,'location_1'), (2, 'location_2'), (3,'location_3');
INSERT INTO b_user_location(user_id, location_id)VALUES(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3);
SELECT
b.user_id,
l.location_id,
l."spatialPoint" AS distance
FROM locations AS l
JOIN b_user_location AS b USING(location_id)
ORDER BY l."spatialPoint" ASC
LIMIT 10 OFFSET 0
[/edit]尝试以下方法:
SELECT
DISTINCT ON(user_id)
DISTINCT ON(location_id)
b.user_id,
.....
SELECT DISTINCT ON(location_id) *
FROM (
SELECT DISTINCT ON(b.user_id)
b.user_id,
l.location_id,
ROUND(distance(transform(PointFromText('POINT(4.0 52.0)', 4326), 26986),transform("spatialPoint", 26986))) AS distance
FROM locations AS l
JOIN b_user_location AS b USING(location_id)
ORDER BY ROUND(distance(transform(PointFromText('POINT(4.0 52.0)', 4326) ASC
)
LIMIT 10 OFFSET 0
它将为您提供10行,其中包含唯一的
user\u id
和唯一的location\u id
,但这些行可能没有最低的距离示例数据或SQLFiddle在这里很有用。添加了Sql和SQLFiddle,tnx;)是的,它很接近,但顺序是必需的,我可以将它包装在另一个子查询中,但我必须看看这在性能方面是如何进行的。