我试图在SQLAlchemy中重写这个mysql查询:
架构:
CREATE TABLE `posts` (
`post_id` INT UNSIGNED PRIMARY AUTO_INCREMENT,
`post_name` VARCHAR(255)
) Engine=InnoDB;
CREATE TABLE `post_tags` (
`tag_id` INT UNSIGNED PRIMARY AUTO_INCREMENT,
`tag_name` VARCHAR(255)
) Engine=InnoDB;
CREATE TABLE `post_tags_map` (
`map_id` INT PRIMARY AUTO_INCREMENT,
`post_id` INT NOT NULL,
`tags_id` INT NOT NULL,
FOREIGN KEY `post_id` REFERENCES `posts` (`post_id`),
FOREIGN KEY `post_id` REFERENCES `post_tags` (`tag_id`)
) Engine=InnoDB;
查询:
SELECT
posts.*,
GROUP_CONCAT( post_tags.tag_name order by post_tags.tag_name ) AS tags
FROM posts
LEFT JOIN posts_tags_map
ON posts_tags_map.post_id = posts.post_id
LEFT JOIN post_tags
ON posts_tags_map.tags_id = posts_tags.tag_id
WHERE posts.post_id = 1
GROUP BY post_id
这就是我所拥有的,但我一直在努力:
1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SEPARATOR /))
rows = DBSession.query(Posts,func.group_concat(Post_Tags.tag_name.op('SEPARATOR')(literal_column('/')))).outerjoin(PostsTagsMap,Posts.post_id==PostsTagsMap.post_id).outerjoin(Post_Tags,PostsTagsMap.tags_id==Post_Tags.tag_id).group_by(Posts.post_id)
答案 0 :(得分:2)
实际上,你做了group_concat位:
DBSession.query(
Posts,
func.group_concat(Post_Tags.tag_name.op('SEPARATOR')(literal_column('/'))))<...>
我不确定到底发生了什么,因为看起来您的架构无效,您的查询有错误的表名,并且判断错误,您尝试将python代码提供给mysql。
对于那些和我一样在google搜索时找到此页面的人,上面的代码位应该会有所帮助,也有源代码,显然:https://groups.google.com/forum/#!msg/sqlalchemy/eNbOoRJ425s/bScfQVat15EJ
答案 1 :(得分:1)
我终于明白了。
>>> str(func.group_concat(Keyword.text.op('separator')(text('","'))))
'group_concat(keywords.text separator ",")'
答案 2 :(得分:1)
浪费了很多时间测试上述示例和其他随机源,以了解如何更改","
中的标准定界字符func.group_concat()
...只是为了遵循直觉并发现语法完全符合您的预期:将定界字符作为参数传递。
如:
from sqlalchemy import func
#write the query: db.session.query(...
...func.group_concat(Table.column_name, "; ")
因此,修改上一个答案的示例:
DBSession.query(
Posts,
func.group_concat(Post_Tags.tag_name, "/"))<...>
注意:这是与Python 3.5,SQLite 3,Flask-SQLAlchemy 2.3.2(已安装SQLAlchemy 1.0.13)一起使用的
答案 3 :(得分:0)
定义自定义函数元素似乎是处理group_concat
方法的最简单方法。
from sqlalchemy.sql import expression
import sqlalchemy
from sqlalchemy.ext import compiler
class group_concat(expression.FunctionElement):
name = "group_concat"
@compiler.compiles(group_concat, 'mysql')
def _group_concat_mysql(element, compiler, **kw):
if len(element.clauses) == 2:
separator = compiler.process(element.clauses.clauses[1])
else:
separator = ','
return 'GROUP_CONCAT(%s SEPARATOR %s)'.format(
compiler.process(element.clauses.clauses[0]),
separator,
)
使用类似这样的东西:
query = select([
table.c.some_column,
expression.label(
'grouped column',
group_concat(
table.c.some_oter_column,
' separator ',
),
),
]).group_by(table.c.some_column)