1

所以我有一些桌子。城市:

CI_ID | City
1     | Aberdeen
2     | Abingdon

国家:

CO_ID | Country
1     | United States of America
2     | Australia

省:

PR_ID | Province
1     | Alabama
2     | South Dakota

城市_省

CI_ID | PR_ID
1     | 2
2     | NULL

城市,国家

CI_ID | CO_ID
1     | 1
2     | 2

通过创建我想要的视图

CI_ID | City     | Province     | Country
1     | Aberdeen | South Dakota | United States of America
2     | Abingdon | NULL         | Australia

而且我无法弄清楚查询。

4

1 回答 1

1

JOIN五个表,但LEFT JOINProvince是这样的:

创建视图:

CREATE VIEW AllData
AS
SELECT
  c.CI_ID, 
  c.city,
  p.Province,
  co.Country     
FROM City c
INNER JOIN City_Province cp ON c.CI_ID = cp.CI_ID
INNER JOIN City_Country cc ON cc.CI_ID = c.CI_ID
INNER JOIN Country co ON cc.CO_ID = co.CO_ID 
LEFT JOIN Province p ON p.PR_ID  = cp.PR_ID;

然后,无论何时要从该视图中进行选择,都可以像普通表格一样从中进行选择:

SELECT * FROM AllData

这会给你:

| CI_ID |     CITY |     PROVINCE |                  COUNTRY |
--------------------------------------------------------------
|     1 | Aberdeen | South Dakota | United States of America |
|     2 | Abingdon |       (null) |                Australia |

SQL 小提琴演示

了解更多信息:

于 2013-01-20T11:30:10.103 回答