简单的SQL Select语句

时间:2018-09-23 22:23:17

标签: sql select

create table Company(cname varchar(30) primary key, country varchar(30));

insert into Company values('GizmoWorks','USA');
insert into Company values('Canon','Japan');
insert into Company values('Hitachi','Japan');
insert into Company values('BizWorks', NULL);
insert into Company values('MonkeyBiz', NULL);

create table Product(pname varchar(30) primary key, price float, category varchar(30), manufacturer varchar(30) references Company);

insert into Product values('Gizmo',19.99,'Gadgets','GizmoWorks');
insert into Product values('PowerGizmo',29.99,'Gadgets','GizmoWorks');
insert into Product values('SingleTouch',149.99,'Photography','Canon');
insert into Product values('Multitouch',203.99,'Household','Hitachi');
insert into Product values('SuperGizmo',49.99, 'Gadgets', 'Hitachi');
insert into Product values('Gizmo-Plus',NULL,'Gadgets','GizmoWorks');
insert into Product values('SingleTouch-Light',89.99,'Photography','Canon');
insert into Product values('SingleTouch++',79.99,'Photography','MonkeyBiz');

我有两个表,应该检索其制造商位于日本的所有产品的名称列表。我是SQL新手,不确定如何执行此操作。有人可以向我解释吗?

这是我到目前为止所拥有的:

SELECT pname
FROM Company, Product
WHERE country='Japan' AND pname='manufacturer'
ORDER BY pname;

1 个答案:

答案 0 :(得分:2)

您可以尝试使用简单的JOIN来达到期望。

SELECT pname
FROM Company c 
JOIN Product p on c.cname = p.manufacturer
WHERE country='Japan' 

注意

  1. 您可以尝试找出哪些列可以连接两个表,然后使用 SQL JOIN来实现,例如,Company.cname = Product.manufacturer中存在关系。

  2. 两个表之间的,是平均值CROSS JOIN,这是一种旧式语法。我建议使用建议,因为JOIN会更清楚表之间的关系。