php - 根据用户位置显示结果

标签 php mysql

我正在开发一个项目,其中用户表具有国家、州和城市列。另一个名为项目的表也包含国家、州和城市列。 现在我想从项目表中获得最相关的结果,其中项目应该具有相同的城市、州和国家。表示 city.state 和 Country 全部匹配的行应该位于顶部。并且只匹配哪个国家/地区应该位于底部。

用户

 ID  |  username  | country | state   | city 

1   |    user1   | country1| state1  |city1
2   |    user2   | country2| state2  |city2
3   |    user3   | country3| state3  |city3

项目

  title | country | state   | city

  p1   | country1| state1  |city1
  p2   | country1| state1  |city2
  p3   | country1| state2  |city2

假设 user1 已登录,我想根据用户位置向该用户显示最相关的结果。 例如,在 p1 行的项目表中,所有国家/地区和城市与用户国家/地区和城市均不匹配。在 p2 中,只有两个国家/地区和州匹配,而在 p3 中,只有国家/地区匹配。我想要执行的操作是按 p1、p2 和 p3 的顺序检索行。

最佳答案

试试这个,希望对你有帮助;)

SQL Fiddle

MySQL 5.6 架构:

CREATE TABLE users
    (`ID` int, `username` varchar(5), `country` varchar(8), `state` varchar(6), `city` varchar(5))
;

INSERT INTO users
    (`ID`, `username`, `country`, `state`, `city`)
VALUES
    (1, 'user1', 'country1', 'state1', 'city1'),
    (2, 'user2', 'country2', 'state2', 'city2'),
    (3, 'user3', 'country3', 'state3', 'city3')
;


CREATE TABLE projects
    (`title` varchar(2), `country` varchar(8), `state` varchar(6), `city` varchar(5))
;

INSERT INTO projects
    (`title`, `country`, `state`, `city`)
VALUES
    ('p1', 'country1', 'state1', 'city1'),
    ('p2', 'country1', 'state1', 'city2'),
    ('p3', 'country1', 'state2', 'city2')
;

查询 1:

select t1.*, t2.*, (t1.country = t2.country) + (t1.state = t2.state) + (t1.city = t2.city) as cnt
from users t1
left join projects t2
on t1.country = t2.country or t1.state = t2.state or t1.city = t2.city
order by t1.id, cnt desc

<强> Results :

| ID | username |  country |  state |  city |  title |  country |  state |   city |    cnt |
|----|----------|----------|--------|-------|--------|----------|--------|--------|--------|
|  1 |    user1 | country1 | state1 | city1 |     p1 | country1 | state1 |  city1 |      3 |
|  1 |    user1 | country1 | state1 | city1 |     p2 | country1 | state1 |  city2 |      2 |
|  1 |    user1 | country1 | state1 | city1 |     p3 | country1 | state2 |  city2 |      1 |
|  2 |    user2 | country2 | state2 | city2 |     p3 | country1 | state2 |  city2 |      2 |
|  2 |    user2 | country2 | state2 | city2 |     p2 | country1 | state1 |  city2 |      1 |
|  3 |    user3 | country3 | state3 | city3 | (null) |   (null) | (null) | (null) | (null) |

关于php - 根据用户位置显示结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37672892/

相关文章:

php - 按照 MySQL IN() 中指定的相同顺序对行进行排序

mysql - 事件记录列中出现频率最高的值

php - 如何使用触发器在SQL中递增?

php - 使用 PDO 和 PHP 在 2 个表中插入多行

php - MySQL 将日期范围排序到开头,然后按其他条件对其他所有内容进行排序

php - 用于执行服务器端脚本的短信

php - MySql 表架构性能问题

mysql - 错误 2002 (HY000) : Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2) help me

php - WordPress/WC session 未进行到下一页

php - 如何修复PHP中的“ header 已发送”错误