0

I have two models one is student_profile where I have university field to show university name. I have a list of universities where I need to update another table called Package only if one of the university exists in table. Table has 1000 records and I need to update all the entries with one query.

  1. If university a, b, c, d exists in student_profile.
  2. Update few "Package" table fields.

My tables:

 +---------------------------+
 | student_profile           |
 +---------------------------+
 | id         | int(11)      |
 | first_name | varchar(45)  |
 | last_name  | varchar(45)  | 
 | university | varchar(45)  | 
 +---------------------------+

 +---------------------------+
 | package                   |
 +---------------------------+
 | student_id  | int(11)     |
 | is_active   | tinyint     |
 | package_type| varchar(45) | 
 +---------------------------+

ForeignKeys in StudentProfile Table:

name = student_package
schema = mydb
Column = student_id
reference Schema = mydb
referenced table = student_profile
referenced column= id

If university exists I need to set is_active=True and set package.student_id as student_profile.id and package.package_type as 'UniverityEnrolled'.

S3S
  • 24,809
  • 5
  • 26
  • 45
Anonymous Coder
  • 107
  • 1
  • 11

2 Answers2

0

Based on what I understand of the question, this may be your solution:

UPDATE package 
    SET is_active = 1,package_type = "UniversityEnrolled"
WHERE student_id IN 
(SELECT id FROM student_profile WHERE university IN ("a","b","c","d"))
Palindromer
  • 854
  • 1
  • 10
  • 29
dev8080
  • 3,950
  • 1
  • 12
  • 18
  • I got this message @dev8080. "You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column To disable safe mode, toggle the option in Preferences -> SQL Editor and reconnect. 0.455 sec" – Anonymous Coder Apr 10 '17 at 18:48
  • This is because though I amusing student_id in where clause that is not the primary key. See http://stackoverflow.com/questions/11448068/mysql-error-code-1175-during-update-in-mysql-workbench. – dev8080 Apr 10 '17 at 19:07
0

To figure something like this out, start with a SELECT that outputs the records to be updated.

Then when it is working, convert to an update statement.

SELECT *
FROM `StudentProfile` a
JOIN `Package` b
ON a.`id` = b.`student_id`
WHERE `university` in ('a','b','c');

UPDATE `StudentProfile` a
    SET `is_active` = 1
JOIN `Package` b
ON a.`id` = b.`student_id`
WHERE `university` in ('a','b','c');
Sloan Thrasher
  • 4,953
  • 3
  • 22
  • 40