douleijiang8111 2018-06-26 16:30
浏览 27
已采纳

如何对列表的所有元素进行“和”运算符? [关闭]

i have the books with different tags (crime, fantastic, dramatic etc.). that's my sql-code:

query := `
    SELECT gotoboox.books.id, gotoboox.books.title 
    FROM gotoboox.books 
    LEFT JOIN gotoboox.books_tags ON gotoboox.books.id = gotoboox.books_tags.book_id 
    LEFT JOIN gotoboox.tags ON gotoboox.books_tags.tag_id = gotoboox.tags.id 
    WHERE gotoboox.tags.title IN ($1) 
    GROUP BY gotoboox.books.title, gotoboox.books.id
`
rows, err := p.Db.Query(query, pq.Array(tags))

but i have got empty result. for example, if i write

..WHERE gotoboox.tags.title IN ('Crime', 'Comedia').. // WITHOUT pg.Array()

its okay.

so, i need pass correctly my pq.Array(tags) to the 'where in'-statement.

P.S. tags is a slice of strings. "tags []string"

  • 写回答

2条回答 默认 最新

  • doudeng8691 2018-06-26 17:38
    关注

    Something like this:

    gotoboox.tags.title IN ('Crime', 'Comedia')
    

    is, more or less, a short way to write:

    gotoboox.tags.title = 'Crime' or gotoboox.tags.title = 'Comedia'
    

    so you don't want to supply an array for the placeholder in IN ($1) unless tags.title is itself an array (which it isn't).

    If you want to pass a slice for the placeholder and use pq.Array, you want to use = ANY(array) in the SQL:

    query := `... WHERE gotoboox.tags.title = any ($1) ...`
    rows, err := p.Db.Query(query, pq.Array(tags))
    

    Alternatively, if tags had n elements then you could build a string like:

    "$1,$2,...,$n"
    

    fmt.Sprintf that into your SQL (which is perfectly safe since you know exactly what's in the strings):

    p := placeholders(len(tags))
    q := fmt.Sprintf("select ... where gotoboox.tags.title in (%s) ...", p)
    

    and then supply values for all those placeholders when you query:

    rows, err := p.DB.Query(q, tags...)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源