英文:
Go and SQL parameters
问题
我对SQL查询的参数有问题。在这种情况下,我从ORDER BY查询中得到了意外的结果。我在OSX上运行PostgreSQL[1]和go v1.0.3。
我有一个包含两列的表:name varchar, gophers int
插入的行是:(“Alice”,2)和(“Bob”,1)
如果我像这样运行查询:rows, err := db.Query("SELECT name FROM foo ORDER BY gophers")
,我得到了我想要的结果(“Bob”,“Alice”)
但是如果我像这样运行它:rows, err = db.Query("SELECT name FROM foo ORDER BY $1", "gophers")
,我按插入顺序得到了结果(“Alice”,“Bob”)
为什么?
完整的代码:http://paste2.org/p/2537881
[1] https://github.com/bmizerany/pq
英文:
I have a problem with parameters to an SQL query. In this case I'm getting unexpected results from an ORDER BY query. I'm running PostgreSQL[1] on OSX and go v1.0.3.
I have a table with two columns: name varchar, gophers int
Inserted rows are: ("Alice", 2) and ("Bob", 1)
If I run my query like this: rows, err := db.Query("SELECT name FROM foo ORDER BY gophers")
I get what I want ("Bob", "Alice")
But if I run it like this rows, err = db.Query("SELECT name FROM foo ORDER BY $1", "gophers")
I get them by insertion order ("Alice", "Bob")
Why?
Complete code: http://paste2.org/p/2537881
答案1
得分: 2
我不知道这是否是一个go问题。在psql中,我执行了以下操作:
PREPARE test (text) AS SELECT name FROM foo ORDER BY $1;
EXECUTE test('a');
然后我得到了以下结果:
name
-------
alice
bob
(2 rows)
我想知道是否可以使用ORDER BY $1。我在谷歌上搜索了一下,但没有找到有用的信息。我知道这不是一个答案,但我觉得这可能是问题所在。我希望能找到一些关于ORDER BY是否支持参数的信息。
英文:
I don't know that this is a go issue at all. In psql I did
PREPARE test (text) AS SELECT name FROM foo ORDER BY $1;
EXECUTE test('a');
and I got
name
-------
alice
bob
(2 rows)
I am wondering if you can do ORDER BY $1. I Google this a bit but could not find anything usefully. I know this is not an answer but it would seem to me this might be the issue. I wish I could find something of if ORDER BY supports parameters.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论