Multiple tuple where clause
blockloop opened this issue ยท 4 comments
I'm trying to recreate this query with squirrel:
SELECT id, name
FROM users
WHERE ((name, age)) IN (('Alex', 10), ('Douglas', 40))
The closest I can come up with is this and it's wrong:
query := sq.Select("id, name").
From("users").
Where(sq.Eq{
"((id, name))": []string{"('Alex', 10)", "('Douglas', 40)"},
})
Squirrel does not support tuples. You could rewrite the query with Or and Eq:
sq.Or{sq.Eq{"name": "Alex", "age": 10}, sq.Eq{"name": "Douglas", "age": 40}}
If you have a fixed number of tuples in your IN clause, you could also write it with Expr:
Expr("((name, age)) IN ((?, ?), (?, ?))", "Alex", 10, "Douglas", 40)
(examples untested)
Closing because @lann's comment is sufficient to solve my issue
sq.Or{sq.Eq{"name": "Alex", "age": 10}, sq.Eq{"name": "Douglas", "age": 40}}
If you need dynamic list of conditions sq.Or{} is an array. May be it will save your time :)
some := sq.Or{}
for _, data := range dataList {
some = append(some, sq.Eq{"key1": data.Value1, "key2": data.Value2})
}
squirrel.Select(*).From("table").Where(some)
// SELECT * FROM table WHERE (key1 = $1 AND key2 = $2 OR key1 = $3 AND key2 = $4)
If you need dynamic list of conditions sq.Or{} is an array. May be it will save your time :)
some := sq.Or{} for _, data := range dataList { some = append(some, sq.Eq{"key1": data.Value1, "key2": data.Value2}) } squirrel.Select(*).From("table").Where(some) // SELECT * FROM table WHERE (key1 = $1 AND key2 = $2 OR key1 = $3 AND key2 = $4)
Thank you,
The idea is correect, but the result is not the same because "AND" has bigger priority than "OR", so in your example need to change "sq.Eq" to "sq.And"
an example from my code
pkConditions := sq.Or{}
for pkIdx := 0; pkIdx < len(primaryKeys); pkIdx++ {
pk := primaryKeys[pkIdx]
pkConditions = append(pkConditions, sq.And{
sq.Eq{"c.location_uid": pk.LocationUID},
sq.Eq{"c.shipment_provider_uid": pk.ShipmentProviderUID},
sq.Eq{"c.shipment_method_uid": pk.ShipmentMethodUID},
})
}
q = q.Where(pkConditions)