Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Multiple tuple where clause #104

Closed
blockloop opened this issue Sep 21, 2017 · 4 comments
Closed

Multiple tuple where clause #104

blockloop opened this issue Sep 21, 2017 · 4 comments

Comments

@blockloop
Copy link

blockloop commented Sep 21, 2017

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)"},
	})
@lann
Copy link
Member

lann commented Sep 21, 2017

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)

@blockloop
Copy link
Author

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}}

@MistaTwista
Copy link

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)

@vkhoroshavin
Copy link

vkhoroshavin commented Nov 1, 2023

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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants