如何创建查询以计算在另一个表中使用外键的次数?

时间:2017-03-02 18:22:24

标签: sql oracle

我有两张桌子:

CREATE TABLE  "OEHR_COUNTRIES" (
    "COUNTRY_ID"    CHAR(2)     CONSTRAINT "OEHR_COUNTRY_ID_NN" NOT NULL ENABLE, 
    "COUNTRY_NAME"  VARCHAR2(40), 
    "REGION_ID"     NUMBER, 
    CONSTRAINT "OEHR_COUNTRY_C_ID_PK"   PRIMARY KEY ("COUNTRY_ID") ENABLE
   )/

CREATE TABLE  "OEHR_LOCATIONS" (
    "LOCATION_ID"       NUMBER(4,0), 
    "STREET_ADDRESS"    VARCHAR2(40), 
    "POSTAL_CODE"       VARCHAR2(12), 
    "CITY"              VARCHAR2(30) CONSTRAINT "OEHR_LOC_CITY_NN" NOT NULL ENABLE, 
    "STATE_PROVINCE"    VARCHAR2(25), 
    "COUNTRY_ID"        CHAR(2), 
     CONSTRAINT "OEHR_LOC_ID_PK" PRIMARY KEY ("LOCATION_ID") ENABLE
   ) 
/

我需要创建一个查询,显示每个国家/地区的名称和ID以及每个国家/地区的位置数量。

2 个答案:

答案 0 :(得分:0)

这是一个简单的left join和聚合:

select c.country_id,
    c.country_name,
    count(*) num_of_locations
from oehr_countries c
left join oehr_locations l on c.country_id = l.country_id
group by c.country_id,
    c.country_name

答案 1 :(得分:0)

select country_name, count(*)
from oehr_countries m, oehr_locations d
where m.country_id = d.country_id