2

请我找不到允许我计算 2 个城市之间的朋友连接数的 SQL 请求。例如,我想知道蒙特利尔和多伦多之间存在多少连接。

这是我数据库中相关表的示例(抱歉,我无法使事情很好地对齐):

Cities桌子

C_ID | Name
C1 | Montreal
C2 | Toronto
C3 | New York

User桌子

U_ID | C_ID | Name
1 | C1 | Jack
2 | C1 | Hilary
3 | C2 | Stefan
4 | C3 | Luis

Friends桌子

F_ID | U_ID1 | U_ID2
1 | 1 | 2
2 | 1 | 3
3 | 2 | 4
4 | 1 | 4
5 | 4 | 3
6 | 3 | 2

如果有人可以帮助我,那就太好了!谢谢

4

1 回答 1

2

你可以这样做:

SELECT COUNT(*) FROM friends 
JOIN user AS u1 ON (u1_id = u1.id) 
JOIN user AS u2 ON (u2_id = u2.id)
JOIN city AS c1 ON (u1.city_id = c1.id)
JOIN city AS c2 ON (u2.city_id = c2.id)

WHERE (c1.name = 'Montreal' AND c2.name = 'Toronto')
OR    (c2.name = 'Montreal' AND c1.name = 'Toronto')

这是针对您的问题的 SQLFiddle 演示:SQLFiddle

于 2013-09-10T08:21:23.173 回答