根据用户位置显示结果

时间:2016-06-07 07:19:10

标签: php mysql

我正在开发一个项目,其中users表包含列Country,state和city。另一个名为projects的表还包含列country,state和city。 现在我希望从项目表中获得最相关的结果,项目应该具有相同的城市,州和国家。表示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检索行。

1 个答案:

答案 0 :(得分:0)

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

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) |