这个 postgresql 如何将 return 查询为 table?

How can this postgresql query return as table?

我正在尝试调用特定课程中的模块,但它 returns 作为错误:用作表达式的子查询返回的行多于一行

查询:

CREATE OR REPLACE FUNCTION course_modules(_courseID integer)

RETURNS SETOF modules AS

$$

BEGIN   

RETURN QUERY SELECT * FROM modules WHERE mod_id =(SELECT module_id from coursemodules WHERE course_id = _courseID);

END

 $$

LANGUAGE 'plpgsql';

课程模块table

 CREATE TABLE coursemodules(
 course_id integer references courses (id) ON DELETE CASCADE,
 module_id integer references modules (mod_id) ON DELETE CASCADE
 );

模块Table

 CREATE TABLE modules(
 documents text   NOT NULL,
 mod_id serial primary key,
 content text   NOT NULL,
 title varchar(50)  NOT NULL
 );

课程Table

 CREATE TABLE courses(
 finishDate Date,
 description text  NOT NULL,
 duration varchar(50)   NOT NULL,
 startDate Date,
 id serial primary key,
 courseName varchar(50)   NOT NULL
 );

这是一个简单的 SQL 语法错误。您正在使用

WHERE mod_id =

但是您可能有不止一行从子查询返回。用户输入:

WHERE mod_id IN 

课程模块table没有限制一门课程只能有一个模块。因此 SELECT module_id from coursemodules WHERE course_id = _courseID 子查询可以 return 多行。

如果你改变mod_id = (SELECT module_id from coursemodules WHERE course_id = _courseID)

mod_id IN (SELECT module_id from coursemodules WHERE course_id = _courseID)

应该可以。否则,您必须向课程模块添加约束 table.