Insert new row - but only if it doesn't exist. If it does exist select the id of the row to be used as foreign key

benwittbrodt :

Tried to be as specific as possible in the title. I have a table restaurants that has a foreign key category_id. I want to enter data into my categories table

CREATE TABLE categories(
 id PRIMARY KEY,
 main_label,
 sub_category, 
 ); 

But only if that data doesn't already exist - which I am doing with

INSERT INTO categories(main_label, sub_category)
SELECT * FROM (SELECT 'yum food', 'alt') AS tmp
WHERE NOT EXISTS (
    SELECT main_label, sub_category FROM categories WHERE mainLabel = 'yum food' && sub_category = 'alt'
) LIMIT 1;

and that's working.

If the data is already there I (say 'yum food' and 'alt') I want to select its' id so I can enter it into my restaurants table.

My current attempt with a TRANSACTION has been awful and I'm running into issues everywhere (as will be glaringly obvious when you read on)

START TRANSACTION;
SET var = SELECT COUNT(*) FROM categories WHERE main_label = 'yum food' && sub_category = 'alt';


IF var > 0 THEN
INSERT INTO categories(main_label, sub_category)
VALUES('yum food', 'alt');
ELSE 
SELECT id FROM categories WHERE main_label = 'yum food' && sub_category = 'alt';
END IF;
COMMIT;

benwittbrodt :

Looks like I've found an answer for it - at least it's doing what I need it to. It checks to see if the entries exist and if it does - stores that id. Then if the entry doesn't exist it will insert it.

DELIMITER $$

CREATE PROCEDURE test(
  name VARCHAR(150),
  sub  VARCHAR(150)
)
BEGIN
  DECLARE cat_id INT DEFAULT 0;

  START TRANSACTION;

  SELECT COUNT(*) 
  INTO @ct
  FROM categories WHERE mainLabel = name && sub_category = sub;

  SET cat_id = @ct;

  IF cat_id =0 THEN
  INSERT INTO categories(mainLabel, sub_category)
  VALUES (name, sub);
  COMMIT;
  ELSE 
  SELECT id 
  INTO @var
  FROM categories WHERE mainLabel = name && sub_category = sub;
  END IF;

END $$
DELIMITER ;


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=360196&siteId=1