简体   繁体   中英

MySQL INSERT… SELECT column count and virtual/aliased columns

I'm trying to insert using a select statement. However, I need to order the sub-select results using a ranking equation. If I create an alias, it throws off the column count. Can I somehow order my results using an equation?

INSERT INTO draft
  ( fk_contrib_id , end_time )
    SELECT pk_contrib_id, UNIX_TIMESTAMP(), (X+Y+Z) AS ranking
    FROM contrib
    ORDER BY ranking DESC
    LIMIT 1

I need the 'ranking' column for sorting, but if I do, the column count is off for the insert. Do I have to use two queries for this?

You could simply change your query to directly use the expression in the ORDER BY clause, like so:

INSERT INTO draft
( fk_contrib_id , end_time )
SELECT pk_contrib_id, UNIX_TIMESTAMP()
FROM contrib
ORDER BY (X+Y+Z) DESC
LIMIT 1

Remove the expression from the SELECT list. And use the expression in the ORDER BY clause.

  ORDER BY X+Y+Z 

It's perfectly valid to ORDER BY expressions that are not in the SELECT list.

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