【问题标题】:How to concatenate ORDER BY in sql如何在sql中连接ORDER BY
【发布时间】:2018-05-26 18:27:03
【问题描述】:

我正在研究 GUI 网格和 sql。我有两个 GUI 按钮,可以根据用户想要信息的顺序单击它们。订单可以由员工Last_nameFirst_name 执行,但不能同时执行。我不确定如何使用它。我想使用连接,但不知道如何。

以下是我尝试做的:

def sort_employees(self, column):
    try:
        cursor = db.cursor()
        display="SELECT * FROM company ORDER BY  '%" + column + "%' "
        cursor.execute(display)
        entry = cursor.fetchall()
        self.display_rows(entry)

另外,如果我只有入口,代码可以正常工作:

display="SELECT * FROM company ORDER BY Last_name"

【问题讨论】:

  • 为什么是 '%" + column + "%' 而不是 " + column + "... % 是 LIKE 语句中最常用的通配符。

标签: python sql database concatenation


【解决方案1】:

在 SQL 中,ORDER BY 子句将列名列表作为参数:

--correct 
ORDER BY firstname, lastname, age

它也可以接受函数输出:

--correct, sort names beginning with a Z first
ORDER BY CASE WHEN first name LIKE 'Z%' THEN 1 ELSE 2 END, firstname

在某些数据库中,放置一个整数序号将按该列排序,从左开始编号,从 1 开始:

--correct, sort by 3rd column then first
ORDER BY 3,1

它不需要包含恰好包含列名的字符串列表:

--incorrect - not necessarily a syntax error but will not sort by any named column
ORDER BY 'firstname', 'lastname', 'age'

也不需要一串csv列名:

--incorrect - again not necessarily a syntax error but won't sort on any of the named columns
ORDER BY 'firstname, lastname, age'

您的代码属于后一类:您将列名转换为字符串。这是错误的。 “不工作的 sql”和“工作的 sql”是非常不同的。将他连接的结果打印到屏幕上,如果您很难从代码中看到它,请查看它们

【讨论】:

    【解决方案2】:

    不知道为什么您的查询字符串中有%,您可能将它与%s syntax for string formatting 混淆了。

    display = "SELECT * FROM company ORDER BY  '%" + column + "%' "
    

    看来你想要的更像是这样的:

    display = "SELECT * FROM company ORDER BY " + column
    

    或者,我更喜欢:

    display = 'SELECT * FROM company ORDER BY {column}'.format(column=column)
    

    当然要小心创建这样的查询,您会面临 SQL 安全漏洞。

    最好使用参数化查询而不是字符串插值/连接,但我不知道您使用的是哪个数据库接口,但通过搜索文档很容易找到。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-15
      • 2021-12-28
      • 1970-01-01
      • 2015-05-21
      • 1970-01-01
      • 2013-12-24
      • 1970-01-01
      相关资源
      最近更新 更多