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 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条