如何从逗号分隔的 ID 字符串构建 WHERE 查询?
How to build a WHERE query from a comma delimited string of ids?
我希望能够构建一个查询,该查询采用一串 uuid 并用逗号将其吐出以生成以下 sql 语句:
uuid
4506ef72-aa17-452b-9456-38d11c71897b,bd46629d-0e8c-4d70-874a-76bfade8ef14,b0c11580-7cde-4a4e-ba0a-30f9de52e3b5
sql
SELECT * FROM my-table WHERE uuid="4506ef72-aa17-452b-9456-38d11c71897b" OR bd46629d-0e8c-4d70-874a-76bfade8ef14 OR b0c11580-7cde-4a4e-ba0a-30f9de52e3b5 ORDER BY created DESC;
我曾尝试在以下方法中使用 sqlkorma 生成此查询,但是我在生成 WHERE 子句时遇到问题。
(defn fetch [uuid]
(->
(korma/select* :my-table)
(korma/order :created :DESC)
(as-> query
(if (not= uuid nil)
(for [id (str/split uuid #",")]
(korma/where query {:uuid id}))
query))
(korma/query-only))
)
试一试:
(defn fetch [uuid]
(-> (korma/select* :my-table)
(korma/order :created :DESC)
(korma/where {:uuid [in (str/split uuid #",")]})
(korma/query-only)))
而不是 OR
-ing 条件,这使用 IN
。
(println (korma/as-sql (fetch "x,x,x")))
SELECT "my-table".* FROM "my-table" WHERE ("my-table"."uuid" IN (?, ?, ?)) ORDER BY "my-table"."created" DESC
我希望能够构建一个查询,该查询采用一串 uuid 并用逗号将其吐出以生成以下 sql 语句:
uuid
4506ef72-aa17-452b-9456-38d11c71897b,bd46629d-0e8c-4d70-874a-76bfade8ef14,b0c11580-7cde-4a4e-ba0a-30f9de52e3b5
sql
SELECT * FROM my-table WHERE uuid="4506ef72-aa17-452b-9456-38d11c71897b" OR bd46629d-0e8c-4d70-874a-76bfade8ef14 OR b0c11580-7cde-4a4e-ba0a-30f9de52e3b5 ORDER BY created DESC;
我曾尝试在以下方法中使用 sqlkorma 生成此查询,但是我在生成 WHERE 子句时遇到问题。
(defn fetch [uuid]
(->
(korma/select* :my-table)
(korma/order :created :DESC)
(as-> query
(if (not= uuid nil)
(for [id (str/split uuid #",")]
(korma/where query {:uuid id}))
query))
(korma/query-only))
)
试一试:
(defn fetch [uuid]
(-> (korma/select* :my-table)
(korma/order :created :DESC)
(korma/where {:uuid [in (str/split uuid #",")]})
(korma/query-only)))
而不是 OR
-ing 条件,这使用 IN
。
(println (korma/as-sql (fetch "x,x,x")))
SELECT "my-table".* FROM "my-table" WHERE ("my-table"."uuid" IN (?, ?, ?)) ORDER BY "my-table"."created" DESC