簡體   English   中英

Rails-JOIN子句不包含具有空外鍵的行

[英]Rails - JOIN clause doesn't include row with null Foreign Key

假設我有此數據(請注意第三本書中的null author_id ):

     Authors
-------------------------
  id  |  name
-------------------------
  1   |  Susan Collins
  2   |  Steven Meyer
-------------------------

   Books
--------------------------------------
 id  |  author_id  |  title
--------------------------------------
 1   |      1      |  Hunger Games
 2   |      2      |  Twilight
 3   |     nil     |  Games of Throne
--------------------------------------

我有一個圖書搜索欄。 我希望可以通過書名和作者名進行搜索。

例如,當我搜索“ Susan”時。 它將返回標題為“ Susan”的書或名稱如“ Susan”的書。

問題是 :當我搜索“游戲”時,它僅返回“飢餓游戲”。 由於author_id為null,因此不會選擇“ author_id游戲”。

我在這里做了SQLFiddle

這是從我的Rails代碼生成的SQL:

SELECT books.* FROM books
  INNER JOIN authors ON authors.id = books.author_id
  WHERE (
    ( LOWER(books.title) LIKE LOWER("%game%") )
    OR
    ( LOWER(authors.name) LIKE LOWER("%game%") )
)

結果僅返回1行:“飢餓游戲”。 沒有“權力的游戲”。

有沒有辦法用空外鍵包含行?

我將接受SQL查詢作為答案,我將嘗試自己弄清楚Rails代碼。

謝謝

[編輯]

這是生成SQL的Rails代碼:(我使用Squeel gem)

search = "%#{params[:search]}%" # the query is taken from param

Books.joins(:author).where {
  ( lower(title) =~ lower(search) ) |
  ( lower(author.name) =~ lower(search) )
}

您想要的是LEFT JOIN而不是內INNER JOINhttp : //blog.codinghorror.com/a-visual-explanation-of-sql-joins/

用Sql Fiddle中的inner替換left,您將獲得帶有或不帶有作者的書籍。

在rails中,可以通過用includes替換joins來實現左joins 因為它使第一個表中的數據保持無關系,所以當您希望加載關系以防止N + 1查詢問題時經常使用它。

也許這就是你所追求的...

SELECT b.* 
  FROM books b
  LEFT
  JOIN authors a
    ON a.id = b.author_id
   AND a.name LIKE '%game%'
 WHERE b.title LIKE '%game%';

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM