我有一张桌子是用来做游戏大厅的。在这个大厅中,用户会被放入他们的连接和他们的级别。在我的SQL语句中,我得到了大厅中的所有用户,它们介于用户级别和连接的+5/-5之间。但是,我希望对此进行排序,这样用户的级别才是最重要的,然后它将查看连接。因此,如果有两个级别相同的用户,它将转而查看连接。也许将来会有更多的列可以用来进一步细化搜索。我已经看到,在这样的单列选择中,我可以使用abs(),但是我不确定这是否也是可能的?
create table users (
id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
connection INT(11),
level INT (11)
);
create table lobby (
id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
user_id INT(11),
CONSTRAINT user_id FOREIGN KEY (id)
REFERENCES users(id)
);
insert into users values (null,5,6);
insert into users values (null,7,10);
insert into users values (null,10,9);
insert into users values (null,10,4);
insert into users values (null,1,8);
insert into lobby values (null,1);
insert into lobby values (null,2);
insert into lobby values (null,3);
insert into lobby values (null,4);
insert into lobby values (null,5);因此,如果我使用user_id =1作为我的用户,我将有以下select语句:
select lobby.id, lobby.user_id, users.connection, users.level
from lobby INNER JOIN users
ON lobby.user_id = users.id
where user_id <> 1 and
users.connection between 0 and 10 and
users.level between 1 and 11
order by abs(connection-5);此select语句返回下表:
| id | user_id | connection | level |
|----|---------|------------|-------|
| 2 | 2 | 7 | 10 |
| 5 | 5 | 1 | 8 |
| 3 | 3 | 10 | 9 |
| 4 | 4 | 10 | 4 |但是,我需要的是以下输出:
| id | user_id | connection | level |
|----|---------|------------|-------|
| 2 | 2 | 7 | 10 |
| 5 | 5 | 1 | 8 |
| 4 | 4 | 10 | 4 |
| 3 | 3 | 10 | 9 |谢谢。
编辑:好的,我目前正在使用abs函数,它运行得很好,但是它可以处理多个字段,正因为如此,我觉得这个语句不是很有效。有更好的方法吗?
发布于 2016-01-23 16:08:04
只需添加另一列,order by abs(connection-5), abs(level-4)是有效的语法:
select lobby.id, lobby.user_id,
users.connection, users.level
from lobby INNER JOIN users
ON lobby.user_id = users.id
where lobby.user_id <> 1
and users.connection between 0 and 10
and users.level between 1 and 11
order by abs(connection-5), abs(level-4);发布于 2016-01-23 11:45:39
试着做这样的事情:
SELECT l.id
,l.user_id # current user ID
,others.id # other user's ID
,others.connection
,others.level
FROM lobby l
INNER JOIN users AS myuser
ON l.user_id = myuser.id
INNER JOIN users AS others
# Remove l.user_id = others.id
ON myuser.id <> others.id
AND ABS(myuser.connection - others.connection) <= 5
AND ABS(myuser.level - others.level) <= 5
WHERE myuser.id = 1
order by ABS(myuser.connection - others.connection),
ABS(myuser.level - others.level);https://dba.stackexchange.com/questions/127090
复制相似问题