2014-03-03 79 views
0

我有这三个表:涉及多个表之间关系的SQL查询。 SQLITE3

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

做一些调查研究,并给它一试。如果您遇到问题,请发布您的SQL,我们会尽力提供帮助。 http://stackoverflow.com/help/how-to-ask –

+1

您将需要'JOIN','GROUP BY','COUNT'和'HAVING'。祝你好运! –

+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) 
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)