CLSQL中具有select函数的子查询

BnM*_*cGn 5 postgresql common-lisp clsql

我正在尝试使用clsql:select函数创建子查询:

CL-USER> (select [books.bookid] 
         :from [books] 
         :where
           (sql-in [books.bookid]
               (select [bookid] 
                   :from [bookauthors]
                   :where 
                   (sql-= [bookauthors.authorid] 120))))
;; 2015-03-07T06:37:08 /books/ => SELECT BOOKID FROM BOOKAUTHORS WHERE (BOOKAUTHORS.AUTHORID = 120)
;; 2015-03-07T06:37:08 /books/ => SELECT BOOKS.BOOKID FROM BOOKS WHERE (BOOKS.BOOKID IN ((157)))
((157))
("bookid")
Run Code Online (Sandbox Code Playgroud)

它可以工作,但是clsql运行两个查询,而不是使用sub-select子句生成一个查询.这不会像让postgresql后端处理整个事情那样高效.

CL-USER> (clsql-sys:db-type-has-subqueries? :postgresql)
T
Run Code Online (Sandbox Code Playgroud)

显然postgresql连接器支持子查询.有没有办法让select函数生成它们?

bob*_*007 2

在上面的调用中,您实际上正在运行内部选择,然后将结果拼接到外部调用中。

您应该使用 sql 表达式而不是函数。如果您(clsql-sys:file-enable-sql-reader-syntax)可以使用方括号来完成此操作,如下所示。

(select [books.bookid] :from [books] :where [in [books.bookid] [select [bookid] :from [bookauthors] :where [= [bookauthors.authorid] 120]]))


另外,您可能希望使用后端,:postgresql-socket3因为它是三个 postgresql clsql 后端中最强大/最新的(它使用cl-postgresql提供的库postmodern通过其套接字 api 版本 3 访问 postgresql。 :posgresql-socket使用 postgres 套接字 api 版本 2 ,并:postgres通过C客户端使用FFI。