5

我有 2 张桌子,Facilities并且Services.

CREATE TABLE Facilities (
facility_id NUMBER(2) NOT NULL,
facility_name VARCHAR2(20) NOT NULL,
CONSTRAINT pk_facil_id PRIMARY KEY (facility_id)
);

CREATE TABLE Services (
service_id NUMBER(2) NOT NULL,
service_name VARCHAR(20) NOT NULL,
service_facility NUMBER(2) NOT NULL,
CONSTRAINT pk_serviceid PRIMARY KEY (service_id)
);

ALTER TABLE Services
add CONSTRAINT fk_servicefacility FOREIGN KEY(service_facility) 
REFERENCES Facilities(facility_id);

如果我尝试将记录输入到“服务”表中,如下所示:

INSERT INTO Services (service_id, service_name, service_facility) 
SELECT 06, 'Rooms', 
(SELECT facility_id, FROM Facilities WHERE facility_name = 'Hotel') 
FROM Dual;

7 个插入语句中有 3 个出现错误“缺少表达式”。缺少什么表情?

4

2 回答 2

8

您发布的 SQL 语句有一个额外的逗号。如果您在 SQL*Plus 中运行该语句,它将抛出 ORA-00936: missing expression 并准确显示错误发生的位置

SQL> ed
Wrote file afiedt.buf

  1  INSERT INTO Services (service_id, service_name, service_facility)
  2  SELECT 06, 'Rooms',
  3  (SELECT facility_id, FROM Facilities WHERE facility_name = 'Boston')
  4* FROM Dual
SQL> /
(SELECT facility_id, FROM Facilities WHERE facility_name = 'Boston')
                     *
ERROR at line 3:
ORA-00936: missing expression

如果删除逗号,则该语句有效

SQL> ed
Wrote file afiedt.buf

  1  INSERT INTO Services (service_id, service_name, service_facility)
  2  SELECT 06, 'Rooms',
  3  (SELECT facility_id FROM Facilities WHERE facility_name = 'Boston')
  4* FROM Dual
SQL> /

1 row created.

但是请注意,我通常更喜欢选择 Stefan 的语法,Facilities而不是dual使用标量子查询进行选择。

于 2012-05-03T22:53:31.283 回答
3

您的插入语句应该是:

INSERT INTO 
    Services 
    (
        service_id, 
        service_name, 
        service_facility
    ) 
SELECT 
    06, 
    'Rooms', 
    facility_id 
FROM 
    Facilities 
WHERE 
    facility_name = 'Hotel'

在当前状态下,我提供的查询将为每个设施的房间添加一个服务记录,名称为 Hotel。

And then add on a join to your 'Dual' table so that you get the correct number of inserts / are getting the correct facilities.

于 2012-05-03T23:02:19.890 回答