H
H
hrvasiliy2016-02-13 13:09:35
MySQL
hrvasiliy, 2016-02-13 13:09:35

How to automate adding a field?

There is a table with 3 columns: language, picture and article. I'm trying to figure out how to implement 1 more column that will have an ID. This ID will report the uniqueness of the article, but not relative to languages. That is, one article in different languages ​​must have the same ID.
There is no possibility to add the same ID when first adding to the database.
It is also not possible to create another 1 table to store the ID.
As an option, assign some kind of ID for the first entry, then get this ID from the link of an image or article and add it to another, new entry. - But it will greatly increase the number of requests.
Maybe there is some option to write some kind of view in the database and use it? Or maybe there are some standard functions, something like "if we are trying to add such and such a value and it is not equal to anything, then increase the value of the field by 1, otherwise write it with the ID that already exists"?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Aleksey Ratnikov, 2016-02-13
@hrvasiliy

Use the UNIQUE delimiter by language and this is your ID:
UPDATE: Here's some sample code for manipulating the ID field when writing pages as a stored procedure:

DELIMITER ;
DROP PROCEDURE IF EXISTS createLocalizedPage;
DELIMITER $
CREATE PROCEDURE createLocalizedPage(
  IN language_in VARCHAR(20),
  IN image_path_in VARCHAR(120),
  IN page_content_in LONGTEXT
) SQL SECURITY INVOKER
BEGIN
  DECLARE var_page_unique_id INT;
  
  START TRANSACTION ;
  IF (exists(SELECT 1 from `table_name` where image_path = image_path_in)) THEN
    SET var_page_unique_id =  (select max(`ID`) + 1 from `table_name`);
  ELSE		
    SET var_page_unique_id = (select `ID` from `table_name` where image_path = image_path_in);		
  END IF;
  
  INSERT INTO `table_name` (`language`, `image_path`, `page_content`, `ID`) VALUES
    (language_in, image_path_in, page_content_in, var_page_unique_id);
  COMMIT ;
END $
DELIMITER ;

Or insert in one request:
INSERT INTO `table_name` (`language`, `image_path`, `page_content`, `ID`) 
VALUES	(
    language_in, 
    image_path_in, 
    page_content_in, 
    CASE 
      WHEN exists(SELECT 1 from `table_name` where image_path = image_path_in) then
        (select `ID` from `table_name` where image_path = image_path_in)
      ELSE
        (select max(`ID`) + 1 from `table_name`)
    END
  );

M
Maxim Popov, 2016-02-13
@maxomato

You can set the column type for languages ​​to SET, and then you can store multiple languages ​​for the same article in that column.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question