简体   繁体   中英

How to concatenate ORDER BY in sql

I am working on a GUI gird and sql. I have two GUI buttons that can be clicked depending on what order the user wants the information. The order can be by Employee Last_name or First_name , but not both. I am not sure how to use that. I am suppose to use concatenation, but am not sure how to.

Below is what I tried to do:

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)

Also, the code works fine if I only have on entry:

display="SELECT * FROM company ORDER BY Last_name"

Not sure why you have % in your query string, it's possible you're confusing it with the %s syntax for string formatting .

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

It seems what you want is more like this:

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

Or, as I prefer:

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

Of course be careful creating queries like this, you're exposed to SQL security vulnerabilities.

It's better to use a parametrised query instead of string interpolation/concatenation, but I don't know which database interface you're using, but it's easy to find that by searching the docs.

In SQL, the ORDER BY clause takes, as arguments, a list of column names:

--correct 
ORDER BY firstname, lastname, age

It can also take function outputs:

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

In some db, putting an integer ordinal on will sort by that column, numbered from the left, starting with 1:

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

It does not take a list of strings that happen to contain column names:

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

Nor does it take a string of csv column names:

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

Your code falls into the latter categories: you're turning the column name into a string. This is wrong. The "not working sql" and the "working sql" are very different. Print the result of he concatenation to screen and look at them if you're having a hard time seeing it from the code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM