我需要选择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", 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,
.....
但这是不允许的。
有人能指出我正确的方向吗?
[编辑] 链接到SqlFiddle http://sqlfiddle.com/#!12/7c090/2/0
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
[/编辑]
答案 0 :(得分:1)
尝试类似:
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
它会为您提供包含唯一user_id
和唯一location_id
的10行,但这些行可能没有最低distance
。