試試這個,你希望幫助;)
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) |
郵政一些示例數據和預期的結果將是更多的幫助。 – Blank
我已更新問題。 – Sama