首頁  >  問答  >  主體

我可以將 json 陣列欄位與 IN 子句結合使用嗎

我有這個正在執行的查詢:

select * 
from housedata 
where JSON_EXTRACT(properties->"$.Type", '$[0]') in ('House', 'Flat');

但是,在某些行中,Type json 陣列中有多個項目,我不想像上面的範例只使用第一個項目。

假設它是 ["House", "Flat"] 我想匹配查詢,而且當它是 ["House", "Tent"] 作為“In”列表中的項目之一時也匹配。 < /p>

這可以在查詢中實現嗎?我試圖找到它,但我一直在尋找在 JSON 數組本身中查找某些內容的示例,但這不是我要尋找的。

P粉066224086P粉066224086178 天前269

全部回覆(1)我來回復

  • P粉373990857

    P粉3739908572024-04-05 09:39:35

    是的,這有效(在 MySQL 8.0.32 中測試):

    select json_extract(properties->'$.Type', '$[0]') IN ('House', 'Flat') as result 
    from housedata;
    +--------+
    | result |
    +--------+
    |      1 |
    +--------+

    如果您想測試 JSON 陣列中與值清單之一相符的任何值,請使用 JSON_OVERLAPS():

    select true from housedata
    where json_overlaps(properties->'$.Type',
      cast('["House","Flat"]' as json));
    +------+
    | true |
    +------+
    |    1 |
    +------+

    當然,如果您不使用 JSON 作為多值屬性,而是使用依賴表並每行儲存一個值,那麼這會簡單得多。

    select ...
    from housedata join housedata_type using (house_id)
    where housedata_type.type in ('House', 'Flat');

    回覆
    0
  • 取消回覆