0

I have bottom MySql query (sql1).

sq1 = 'select course_id, creator_id, max(course_num) + 1, recordid 
  ' from Courses where recordid in' \
  ' (' + ','.join(map(str, RecordMatch1)) + ') group by recordid'
cursor.execute(sql1)

BTW, RecordMatch1 is an object that has matching data from other previous queries.

I am trying to see if this is possible; (select * from sql1) portion.

sql2 = ' insert into Courses (course_id, creator_id, course_num, record_id) '\
   ' Values ( select * from sql1)'
cursor.execute(sql2)

Or do I have to express everything rather than using (Select * )?

What is best practice?

Java
  • 1,208
  • 3
  • 15
  • 29
  • You don't write `INSERT INTO table1 (col, col, ...) SELECT (col, col, ...) FROM table2` without the word "values". – khelwood Aug 28 '17 at 17:36

3 Answers3

2

You can do this, but you should specify columns in case of schema changes.

jonathan.ihm
  • 108
  • 1
  • 1
  • 8
1

Just need to confirm you are trying to run a select query and insert its output to a insert query. If that is the case this appears to be good.

Daniyal Ahmed
  • 715
  • 5
  • 11
1

yes, you can but you should do something like

sql = "SELECT course_id, creator_id, course_num, record_id FROM Courses" 
all = cursor.fetchall()
for i in range(len(all))
    sql1 = "INSERT INTO Courses (course_id, creator_id, course_num, record_id) VALUES (%s, %s, %s, %s)"
    cursor.execute(sql1, (all[i]['Key'], all[i]['Key2'], all[i]['Key3'], all[i]['Key3']))

you can change the select like you want, remember that return a dictionary so take care about the keys, add print(all) to see what happen with the select and see the keys of each column

Mauricio Cortazar
  • 4,049
  • 2
  • 17
  • 27