SQL Join操作使用咨询:多表关联查询冰激凌与制造商表数据
问题1解答
你写的不带WHERE子句的查询语句SELECT ice_cream_id, ice_cream_name, manufacturer_name FROM ice_cream, manufacturer; 实际返回的是笛卡尔积结果:数据库会把ice_cream表的每一行和manufacturer表的每一行任意组合,最终得到4款冰激凌×3个制造商共12条记录,完全不符合你要的冰激凌和对应制造商一一匹配的需求。
你只需要在WHERE子句中添加等值连接条件,让两张表通过公共关联字段manufacturer_id做匹配,仅保留两个表中制造商ID相等的行,再加上排序规则即可得到正确结果,完整语句如下:
SELECT ice_cream.ice_cream_id, ice_cream.ice_cream_name, manufacturer.manufacturer_name FROM ice_cream, manufacturer WHERE ice_cream.manufacturer_id = manufacturer.manufacturer_id ORDER BY ice_cream.ice_cream_id ASC;
问题2解答
该需求同样需要使用WHERE子句实现,你只需要在原有等值连接条件的基础上,用AND拼接制造成本的筛选条件即可,完整语句如下:
SELECT ice_cream.ice_cream_id, ice_cream.ice_cream_name, ice_cream.manufacturing_cost, manufacturer.manufacturer_name FROM ice_cream, manufacturer WHERE ice_cream.manufacturer_id = manufacturer.manufacturer_id AND ice_cream.manufacturing_cost > 1;
内容的提问来源于stack exchange,提问作者Elja Suhonen
相关产品推荐
相关产品推荐

