Question

I have a table for an event, and I have just made a new table for ticketing_information. Each event in the event table should have a ticketing_information, referenced by a unique id. I'm new to sql, so forgive me if this is a very basic/repeated question, but how should I go about making the migration add a new row to the ticketing_information table for every existing event, and giving the event the generated ticketing_information id?

If it helps, some of my sql is attached:

CREATE TABLE `ticketing_information` (
  `id` INT(10) unsigned NOT NULL AUTO_INCREMENT,
  `tickets_available` BOOLEAN DEFAULT TRUE NOT NULL,
  `ticketing_url` VARCHAR(2000) DEFAULT NULL,
  `additional_info_url` VARCHAR(2000) DEFAULT NULL,
  PRIMARY KEY (`id`);)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8; 

ALTER TABLE event
ADD COLUMN ticketing_information_id Int(10) unsigned DEFAULT NULL;

(This is a very stripped-down version of the code, but it should help illustrate the behavior I want)

I was thinking it should be something along the lines of

UPDATE event SET
ticketing_information_id = SELECT `id` FROM `ticketing_information` WHERE <some way of making a new ticketing_information?>;

But I don't really know what I'm doing :)

Was it helpful?

Solution

how i would perform something like, adding a new non-nullable column to an existing table, would be:

  • adding that column in first step as nullable, otherwise you will not get the rdbms to modify the table, because it will violate the not null constraint.

  • updating the new column to the data you want it to have

    UPDATE event e 
    SET e.ticketing_information_id = (SELECT `id` FROM `ticketing_information` WHERE id = e.id)
    

    Your update needs to tell the inner select, which row it is currently updating, so you are able to filter only the data of that particular row in the inner select.

  • modifying the column to be not null

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top