涉及多个表之间关系的SQL查询。 SQLITE3

时间:2014-03-03 02:05:00

标签: sql database sqlite

我有这三个表:

create table Nation ("nationkey" integer, 
                     "name" text, 
                     "regionkey" integer, 
                     "comment" text, 
                     "null" text,
                     foreign key (regionkey) references Region);

create table Supplier ("suppkey" integer, 
                       "name" text, 
                       "address" text, 
                       "nationkey" integer, 
                       "phone" text, 
                       "acctbal" real, 
                       "comment" text, 
                       "null" text,
                       foreign key (nationkey) references Nation);

create table Customer ("custkey" integer, 
                       "name" text, 
                       "address" text, 
                       "nationkey" integer, 
                       "phone" text, 
                       "acctbal" real, 
                       "mktsegment" text, 
                       "comment" text, 
                       "null" text, 
                       foreign key (nationkey) references Nation);

我必须编写一个sql查询,它返回拥有比供应商更多客户的国家的名称。查询需要在Sqlite3中。我是sql的新手,不知道怎么做这个。

2 个答案:

答案 0 :(得分:0)

对于特定国家/地区密钥,您可以使用COUNT获取相应客户的数量:

SELECT COUNT(*)
FROM Customer
WHERE nationkey = ?

供应商也一样。

然后,您可以将这些COUNT个查询用作correlated subqueries来比较每个Nation记录的这些值:

SELECT name
FROM Nation
WHERE (SELECT COUNT(*)
       FROM Customer
       WHERE nationkey = Nation.nationkey) >
      (SELECT COUNT(*)
       FROM Supplier
       WHERE nationkey = Nation.nationkey)

答案 1 :(得分:0)

使用显式JOIN的另一种可能的解决方案:

SELECT n.name
FROM Nation n
JOIN Customer c ON n.nationkey = c.nationkey
JOIN Supplier s ON n.nationkey = s.nationkey
GROUP BY n.name
HAVING COUNT(c.nationkey) > COUNT(s.nationkey)