SQL查询从多个表中选择相同的字段

时间:2015-11-04 17:44:47

标签: mysql sqlite

我在架构

中定义了三个表
donuts (name: string, price: integer) 
grocery (no: string, gname: string, minCredit: integer) 
distributor (dname: string, gno: string, deliverydate: date)

distributor.dname和distributor.gno是引用甜甜圈和杂货的外键,哪些键是名称而且没有相应的我在遇到2个查询时遇到问题我想写:

我正在尝试展示可以在同一家杂货店找到的甜甜圈对(即所有携带一个甜甜圈的商店都由另一家购买,反之亦然)。输出模式应该是(donutname1,donutname2)

我试过的是:

select d.name as donutname1, d.name as donutname2
from donuts d, grocery g, distributor dd
where d.name IN  
    (select  d.name 
     from donuts d, grocery g, distributor dd 
     where d.name = dd.name)

这似乎错了,似乎给了我错误的结果。我如何查询这两个名称并获得结果?

1 个答案:

答案 0 :(得分:0)

尝试使用您的数据进行以下实验:

SELECT aa.name AS donutname1, bb.name AS donutname2
FROM dunuts AS aa
INNER JOIN donuts AS bb
ON aa.name = bb.name
INNER JOIN distributor AS cc
ON aa.name = cc.dname
INNER JOIN distributor AS dd
ON bb.name = cc.dname
WHERE cc.gno = dd.gno;