我对此查询有疑问
SELECT DISTINCT(oth.book) FROM book_meta_keywords oth,
(SELECT bmk.meta_keyword AS metaKeyword, bmk.book AS book FROM books b
INNER JOIN customers_books cvb ON cvb.book = b.id
INNER JOIN book_meta_keywords bmk ON bmk.book = b.id
WHERE cvb.customer = 1 ) AS allCustomerPurchasedBooksMeta
INNER JOIN books b ON b.id = oth.book
WHERE oth.meta_keyword = allCustomerPurchasedBooksMeta.metaKeyword AND oth.book != allCustomerPurchasedBooksMeta.book AND b.status = 'GOOD'
对于此查询,我遇到了以下错误。
错误:对表“ oth”的FROM子句条目的引用无效 第6行:b.id = oth.book上的INNER JOIN图书 ^ 提示:表“ oth”有一个条目,但是不能从查询的这一部分中引用它。 ,时间:0.002000秒
但是,如果我运行以下查询,它将起作用
SELECT DISTINCT(oth.book) FROM book_meta_keywords oth,
(SELECT bmk.meta_keyword AS metaKeyword, bmk.book AS book FROM books b
INNER JOIN customers_books cvb ON cvb.book = b.id
INNER JOIN book_meta_keywords bmk ON bmk.book = b.id
WHERE cvb.customer = 1 ) AS allCustomerPurchasedBooksMeta
WHERE oth.meta_keyword = allCustomerPurchasedBooksMeta.metaKeyword AND oth.book != allCustomerPurchasedBooksMeta.book
任何人都可以帮助我为什么...查询基本上是在尝试根据基于购买的图书的meta关键字来获取相似的图书。
谢谢。
答案 0 :(得分:1)
您缺少join
SELECT DISTINCT oth.book FROM book_meta_keywords oth join
(SELECT bmk.meta_keyword AS metaKeyword, bmk.book AS book FROM books b
INNER JOIN customers_books cvb ON cvb.book = b.id
INNER JOIN book_meta_keywords bmk ON bmk.book = b.id
WHERE cvb.customer = 1 ) AS allCustomerPurchasedBooksMeta
on oth.meta_keyword = allCustomerPurchasedBooksMeta.metaKeyword and
oth.book != allCustomerPurchasedBooksMeta.book
INNER JOIN books b ON b.id = oth.book
WHERE b.status = 'GOOD'
答案 1 :(得分:1)
这是您的FROM
子句:
FROM
book_meta_keywords oth,
(SELECT ... FROM ... WHERE ...) AS allCustomerPurchasedBooksMeta
INNER JOIN books b ON b.id = oth.book
您正在混合使用显式联接和隐式联接(后者用逗号表示)。别。它们具有不同的优先规则,查询计划者最终会在看到oth
之前评估第二个条件。
关于如何解决这个问题:假设逻辑确实是您想要的,那就是横向联接:
FROM
book_meta_keywords oth
CROSS JOIN LATERAL (SELECT ... FROM ... WHERE ...) AS allCustomerPurchasedBooksMeta
INNER JOIN books b ON b.id = oth.book
但是,我怀疑您的查询可以进一步简化。您可能要问另一个问题,以说明查询的目的并提供一个最小的可复制示例。
答案 2 :(得分:1)
它可以工作:
SELECT DISTINCT oth.book
FROM book_meta_keywords oth
INNER JOIN books b ON b.id = oth.book
, (SELECT bmk.meta_keyword AS metaKeyword, bmk.book AS book
FROM books b
INNER JOIN customers_books cvb ON cvb.book = b.id
INNER JOIN book_meta_keywords bmk ON bmk.book = b.id
WHERE cvb.customer = 1 ) AS allCustomerPurchasedBooksMeta
WHERE oth.meta_keyword = allCustomerPurchasedBooksMeta.metaKeyword
AND oth.book != allCustomerPurchasedBooksMeta.book
AND b.status = 'GOOD'
但这能满足您的需求吗?