Skip to content

Instantly share code, notes, and snippets.

@helart
Created August 21, 2020 17:04
Show Gist options
  • Save helart/54e3c63645fbd53fd7ccfae50799f179 to your computer and use it in GitHub Desktop.
Save helart/54e3c63645fbd53fd7ccfae50799f179 to your computer and use it in GitHub Desktop.
MySQL рецепты
-- Временные таблицы в MySQL
-- Создание пустой таблицы:
CREATE TEMPORARY TABLE `tmp_table` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`price` decimal(11,2) unsigned NOT NULL DEFAULT '0.00',
`sef` varchar(255) NOT NULL,
`text` text NOT NULL,
`approve` tinyint(1) NOT NULL DEFAULT '1',
`date_add` int(11) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
-- Создание временной таблицы из структуры другой:
CREATE TEMPORARY TABLE `tmp_table` LIKE `prods`;
-- Клонирование таблицы:
CREATE TEMPORARY TABLE `tmp_table` SELECT * FROM `prods`;
-- Создание и наполнение из нескольких таблиц:
CREATE TEMPORARY TABLE `tmp_table`
SELECT
`prods`.`name`,
`urls`.`sef`
FROM
`prods`
LEFT JOIN
`urls`
ON
`prods`.`id` = `urls`.`prods_id`
WHERE
`prods`.`approve` = 1;
-- ##########################################################
-- Получить текст до дефиса
SELECT SUBSTRING(`field`, 1, (POSITION("-" IN `field`) -1)) AS `new_field` FROM `table`;
-- Замена в тексте
UPDATE `table` SET `field` = REPLACE(`field`, 'старый текст', 'новый текст');
-- Возраст (кол-во лет) из даты YYYY-MM-DD
SELECT TIMESTAMPDIFF(YEAR, `birth_date`, CURDATE()) AS `age` FROM `table`;
-- Или из трех отдельных полей даты рождения:
SELECT TIMESTAMPDIFF(YEAR, CONCAT_WS('-', `year`, `months`, `day`), CURDATE()) AS `age` FROM `table`;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment