简体   繁体   中英

MySQL INSERT SELECT. Ordering insert by count but don't actually insert the count number

Sorry for the ridiculous title!

Is it possible to run a MySQL INSERT SELECT query where the 'SELECT' portion includes a COUNT() function (to benefit from a HAVING clause) -- this creates an unmatching column count on the INSERT portion.

For example:

INSERT INTO my_log (user_id, date_finished) 
SELECT COUNT(id) AS count, user_id, '2011-05-31 00:00:00'
FROM assignments WHERE assignment_type = 10 
GROUP BY user_id
HAVING count >=10 

I want to insert into the TABLE my_log a date for users who've completed 10 assignments of the type 10. In reality I'm expanding on this slightly so it's important I use the COUNT and HAVING to find only users who have completed 10 or more assignments. But my problem remains that I'm trying to insert 3 columns into a declared 2 columns because of the COUNT() function, so I'm looking for a way to benefit from the COUNT but not return it in my data set / considered in the insertion.

Thanks for any help:)

Try with:

INSERT INTO my_log ( user_id, date_finished) 
SELECT user_id, '2011-05-31 00:00:00'
FROM assignments WHERE assignment_type = 10 
GROUP BY user_id
HAVING ( COUNT(id) ) >=10 

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