简体   繁体   中英

MySQL: How can I order a table based upon the difference of two values using ALTER TABLE

I want to sort a MySQL table using ALTER TABLE (so it stays sorted), and it works fine when I simply put in 1 column name like this:

ALTER TABLE data ORDER BY upvotes DESC; 

But I want to sort it based upon the difference of two values, and when I do that I get "Unrecognized alter operation."

This is the code I want to work:

ALTER TABLE data ORDER BY (upvotes-downvotes) DESC; 

Is there a way to do this, or am I just getting the syntax wrong? Thanks in advance!

As mysql documentation on alter table says (highlighting is mine):

ORDER BY syntax permits one or more column names to be specified for sorting, each of which optionally can be followed by ASC or DESC to indicate ascending or descending sort order, respectively. The default is ascending order. Only column names are permitted as sort criteria; arbitrary expressions are not permitted. This clause should be given last after any other clauses.

As @juergend suggested in his comment, the possible workaround is to store the results of the calculation in a field and use that for sorting.

Also, I'm not sure why you are still stuck with myisam table type. I would definitely consider switching over to innodb.

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