INSERT INTO with empty results from SELECT - mysql

I'm trying to insert into table A from the results gather from table B:
INSERT INTO A (x, y, created_at)
(SELECT x, "something", a_timestamp
FROM B WHERE c IS NULL AND a_timestamp > NOW())
The issue is that, for some instances
(SELECT x, "something", a_timestamp
FROM B WHERE c IS NULL AND a_timestamp > NOW())
doesn't return any records (which is okay), but then the other INSERT fails.
How can I cover myself from that scenario?
Thanks!

I can't reproduce the error:
mysql> DROP TABLE IF EXISTS `tbl_test`;
Query OK, 0 rows affected, 1 warning (0.00 sec)
mysql> CREATE TABLE IF NOT EXISTS `tbl_test` (
-> `id` TINYINT
-> );
Query OK, 0 rows affected (0.00 sec)
mysql> INSERT INTO `tbl_test`
-> SELECT 1
-> FROM DUAL
-> WHERE 0 = 0;
Query OK, 1 row affected (0.00 sec)
Records: 1 Duplicates: 0 Warnings: 0
mysql> SELECT `id` FROM `tbl_test`;
+------+
| id |
+------+
| 1 |
+------+
1 row in set (0.00 sec)
mysql> INSERT INTO `tbl_test`
-> SELECT 1
-> FROM DUAL
-> WHERE 0 = 1;
Query OK, 0 rows affected (0.00 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> SELECT `id` FROM `tbl_test`;
+------+
| id |
+------+
| 1 |
+------+
1 row in set (0.00 sec)
UPDATE
mysql> DROP TABLE IF EXISTS `tbl_test`;
Query OK, 0 rows affected (0.00 sec)
mysql> CREATE TABLE IF NOT EXISTS `tbl_test` (
-> `id` TINYINT
-> );
Query OK, 0 rows affected (0.00 sec)
mysql> INSERT INTO `tbl_test`
-> (`id`)
-> VALUES
-> (101);
Query OK, 1 row affected (0.00 sec)
mysql> SELECT `id`
-> FROM `tbl_test`;
+------+
| id |
+------+
| 101 |
+------+
1 row in set (0.00 sec)
mysql> INSERT INTO `tbl_test`
-> SELECT `id` + 1
-> FROM `tbl_test`
-> WHERE `id` > 100;
Query OK, 1 row affected (0.00 sec)
Records: 1 Duplicates: 0 Warnings: 0
mysql> SELECT `id`
-> FROM `tbl_test`;
+------+
| id |
+------+
| 101 |
| 102 |
+------+
2 rows in set (0.00 sec)
mysql> INSERT INTO `tbl_test`
-> SELECT `id` + 1
-> FROM `tbl_test`
-> WHERE `id` < 100;
Query OK, 0 rows affected (0.00 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> SELECT `id`
-> FROM `tbl_test`;
+------+
| id |
+------+
| 101 |
| 102 |
+------+
2 rows in set (0.00 sec)
See db-fiddle.

You can use INSERT IGNORE INTO to address your issue.
For example:
INSERT IGNORE INTO A (x, y, created_at)
(SELECT x, "something", a_timestamp
FROM B WHERE c IS NULL AND a_timestamp > NOW())
More info can be found here

"INSERT INTO A (x, y, created_at)
(SELECT x, \"something\", a_timestamp
FROM B WHERE c IS NULL AND a_timestamp > \"#{current_time}\")
To
"INSERT INTO A (x, y, created_at)
(SELECT x, \"something\", a_timestamp
FROM B WHERE c IS NULL AND a_timestamp > \"#{current_time}\")
AND (SELECT count(x) FROM B WHERE c IS NULL AND a_timestamp > \"#{current_time}\")) > 0"

Related

how to update records of two different table present in two different database through single procedure in mysql?

CREATE PROCEDURE p_samp(
IN p_id INT,IN p_table_choice VARCHAR(10)
)
BEGIN
CASE p_table_choice
WHEN p_table_choice = 'A' THEN
USE database1;
update sample1
SET name = 'sam'
WHERE id = p_id;
WHEN p_table_choice = 'B' THEN
USE database2;
update sample2
SET name = 'sam'
WHERE id = p_id;
ELSE
BEGIN
END;
END CASE ;
END;
You can try:
CREATE PROCEDURE p_samp(
IN p_id INT,IN p_table_choice VARCHAR(10)
)
BEGIN
CASE p_table_choice
WHEN p_table_choice = 'A' THEN
update database1.sample1
SET name = 'sam'
WHERE id = p_id;
WHEN p_table_choice = 'B' THEN
update database2.sample2
SET name = 'sam'
WHERE id = p_id;
ELSE
BEGIN
END;
END CASE ;
END;
I tried a sample procedure and it worked.
Here's a sample procedure I tried to perform a similar update between two databases learning and pricing >>
CREATE PROCEDURE `xxxx`(A int(1))
begin
case A
when 1 then update learning.GAUL set user='OBELIX' where id=1;
when 0 then update pricing.K1 set amntIN='500' where account=1;
else
select 'DUMMY';
END CASE;
END
So basically the first update shall result in one affected row and the 2nd one shall result in 2 affected rows.
I call them:
mysql> call xxxx(1);
Query OK, 1 row affected (0.05 sec)
mysql> call xxxx(0);
Query OK, 3 rows affected (0.12 sec)
mysql> call xxxx(3);
+-------+
| DUMMY |
+-------+
| DUMMY |
+-------+
1 row in set (0.00 sec)
The following script works as expect:
mysql> DROP PROCEDURE IF EXISTS `p_samp`;
Query OK, 0 rows affected (0.00 sec)
mysql> DROP TABLE IF EXISTS `database2`.`sample2`,
-> `database1`.`sample1`;
Query OK, 0 rows affected (0.00 sec)
mysql> DROP DATABASE IF EXISTS `database2`;
Query OK, 0 rows affected (0.00 sec)
mysql> DROP DATABASE IF EXISTS `database1`;
Query OK, 0 rows affected (0.00 sec)
mysql> CREATE DATABASE IF NOT EXISTS `database1`;
Query OK, 1 row affected (0.00 sec)
mysql> CREATE DATABASE IF NOT EXISTS `database2`;
Query OK, 1 row affected (0.00 sec)
mysql> CREATE TABLE IF NOT EXISTS `database1`.`sample1` (
-> `id` SERIAL,
-> `name` VARCHAR(255)
-> );
Query OK, 0 rows affected (0.00 sec)
mysql> CREATE TABLE IF NOT EXISTS `database2`.`sample2` (
-> `id` SERIAL,
-> `name` VARCHAR(255)
-> );
Query OK, 0 rows affected (0.00 sec)
mysql> INSERT INTO `database1`.`sample1`
-> (`name`)
-> VALUES
-> ('sam in db1');
Query OK, 1 row affected (0.00 sec)
mysql> INSERT INTO `database2`.`sample2`
-> (`name`)
-> VALUES
-> ('sam in db2');
Query OK, 1 row affected (0.00 sec)
mysql> DELIMITER //
mysql> CREATE PROCEDURE `p_samp` (
-> `p_id` BIGINT UNSIGNED,
-> `p_table_choice` CHAR(1)
-> )
-> BEGIN
-> CASE `p_table_choice`
-> WHEN 'A' THEN
-> UPDATE `database1`.`sample1`
-> SET `name` = 'sam'
-> WHERE `id` = `p_id`;
-> WHEN 'B' THEN
-> UPDATE `database2`.`sample2`
-> SET `name` = 'sam'
-> WHERE `id` = `p_id`;
-> END CASE;
-> END//
Query OK, 0 rows affected (0.00 sec)
mysql> DELIMITER ;
mysql> SELECT
-> `id`,
-> `name`
-> FROM
-> `database1`.`sample1`;
+----+------------+
| id | name |
+----+------------+
| 1 | sam in db1 |
+----+------------+
1 row in set (0.00 sec)
mysql> SELECT
-> `id`,
-> `name`
-> FROM
-> `database2`.`sample2`;
+----+------------+
| id | name |
+----+------------+
| 1 | sam in db2 |
+----+------------+
1 row in set (0.00 sec)
mysql> CALL `p_samp`(1, 'A');
Query OK, 1 row affected (0.00 sec)
mysql> SELECT
-> `id`,
-> `name`
-> FROM
-> `database1`.`sample1`;
+----+------+
| id | name |
+----+------+
| 1 | sam |
+----+------+
1 row in set (0.00 sec)
mysql> SELECT
-> `id`,
-> `name`
-> FROM
-> `database2`.`sample2`;
+----+------------+
| id | name |
+----+------------+
| 1 | sam in db2 |
+----+------------+
1 row in set (0.00 sec)
mysql> CALL `p_samp`(1, 'B');
Query OK, 1 row affected (0.00 sec)
mysql> SELECT
-> `id`,
-> `name`
-> FROM
-> `database1`.`sample1`;
+----+------+
| id | name |
+----+------+
| 1 | sam |
+----+------+
1 row in set (0.00 sec)
mysql> SELECT
-> `id`,
-> `name`
-> FROM
-> `database2`.`sample2`;
+----+------+
| id | name |
+----+------+
| 1 | sam |
+----+------+
1 row in set (0.00 sec)

mysql json datatype searching for a value inside the array

I have a column in a MySQL table that is of json type and the values in that column are a simple 1D array (e.g. [1,2,3,4,5]). How do I use the json_contains function to return all rows that contain the value "5" in the json array?
Try:
mysql> DROP TABLE IF EXISTS `tbl`;
Query OK, 0 rows affected, 1 warning (0.00 sec)
mysql> CREATE TABLE IF NOT EXISTS `tbl` (
-> `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> `json` JSON NOT NULL
-> );
Query OK, 0 rows affected (0.00 sec)
mysql> INSERT INTO `tbl`
-> (`json`)
-> VALUES
-> ('[1,2,3,4,5]'),
-> ('[1,2,3,4]'),
-> ('[1,2]'),
-> ('[1]'),
-> ('[1,5]');
Query OK, 5 rows affected (0.01 sec)
Records: 5 Duplicates: 0 Warnings: 0
mysql> SELECT
-> `id`,
-> `json`
-> FROM
-> `tbl`
-> WHERE
-> JSON_CONTAINS(`json`, '5');
+----+-----------------+
| id | json |
+----+-----------------+
| 1 | [1, 2, 3, 4, 5] |
| 5 | [1, 5] |
+----+-----------------+
2 rows in set (0.00 sec)
See db-fiddle.
UPDATE
mysql> DROP TABLE IF EXISTS `tbl`;
Query OK, 0 rows affected (0.00 sec)
mysql> CREATE TABLE IF NOT EXISTS `tbl` (
-> `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> `json` JSON NOT NULL
-> );
Query OK, 0 rows affected (0.00 sec)
mysql> INSERT INTO `tbl`
-> (`json`)
-> VALUES
-> ('["1","2","3","4","5"]'),
-> ('["1","2","3","4"]'),
-> ('["1","2"]'),
-> ('["1"]'),
-> ('["1","5"]');
Query OK, 5 rows affected (0.00 sec)
Records: 5 Duplicates: 0 Warnings: 0
mysql> SELECT
-> `id`,
-> `json`
-> FROM
-> `tbl`
-> WHERE
-> JSON_CONTAINS(`json`, '"5"');
+----+---------------------------+
| id | json |
+----+---------------------------+
| 1 | ["1", "2", "3", "4", "5"] |
| 5 | ["1", "5"] |
+----+---------------------------+
2 rows in set (0.00 sec)
See db-fiddle.

MySQL: delete row if exist in other table with condition

I need to delete rows from 'old_battles' table, if it exists in 'battles' table with condition:
delete the row from 'old_battles' if it existed in 'battles' and 'old_battles.status = "finished"'
note: old_battles.id = battles.id
tables structure:
battles:
id status
1 finished
2 cancelled
3 on progress
4 finished
5 finished
old_battles:
id status
1 finished
2 cancelled
3 on progress
4 finished
5 finished
my query:
delete from old_battles
where old_battles.id in
(
select ob2.id
from old_battles ob2,battles b
where ob2.id = b.id
and ob2.status = 'finished'
)
Consider the following
mysql> create table battles (id int, status varchar(100));
Query OK, 0 rows affected (0.09 sec)
mysql> insert into battles values
-> (1,'finished'),
-> (2,'cancelled'),
-> (3,'on progress'),
-> (4,'finished'),
-> (5,'finished');
Query OK, 5 rows affected (0.03 sec)
Records: 5 Duplicates: 0 Warnings: 0
mysql> create table old_battles like battles;
Query OK, 0 rows affected (0.11 sec)
mysql> insert into old_battles values
-> (1,'finished'),
-> (2,'cancelled'),
-> (3,'on progress'),
-> (4,'finished'),
-> (5,'finished');
Query OK, 5 rows affected (0.03 sec)
Records: 5 Duplicates: 0 Warnings: 0
The following is the query to delete
delete ob from old_battles ob
join battles b on b.id = ob.id where ob.status = 'finished';
mysql> select * from old_battles ;
+------+-------------+
| id | status |
+------+-------------+
| 2 | cancelled |
| 3 | on progress |
+------+-------------+
2 rows in set (0.00 sec)

MySQL Insert Select - NOT NULL fields

Oh hey there,
I am trying to load data into a table via a INSERT... SELECT statement, but I am having issues with MySQL handling NULL values.
In the below example, table1 is the source and table2 is the destination (Note that table2 has more constraints on the description field):
mysql> drop table if exists table1;
Query OK, 0 rows affected (0.03 sec)
mysql> drop table if exists table2;
Query OK, 0 rows affected (0.00 sec)
mysql> create table if not exists table1 (
-> id int not null auto_increment,
-> description varchar(45),
-> primary key (`id`)
-> );
Query OK, 0 rows affected (0.03 sec)
mysql> create table if not exists table2 (
-> id int not null auto_increment,
-> description varchar(45) not null,
-> primary key (`id`),
-> unique index `unique_desc` (`description`)
-> );
Query OK, 0 rows affected (0.01 sec)
mysql> insert ignore into table1
-> (description)
-> values("stupid thing"),
-> ("another thing"),
-> (null),
-> ("stupid thing"),
-> ("last thing");
Query OK, 5 rows affected (0.00 sec)
Records: 5 Duplicates: 0 Warnings: 0
mysql> select * from table1;
+----+---------------+
| id | description |
+----+---------------+
| 1 | stupid thing |
| 2 | another thing |
| 3 | NULL |
| 4 | stupid thing |
| 5 | last thing |
+----+---------------+
5 rows in set (0.00 sec)
mysql> insert ignore into table2
-> (description)
-> select description
-> from table1;
Query OK, 4 rows affected, 1 warning (0.01 sec)
Records: 5 Duplicates: 1 Warnings: 1
mysql> select * from table2;
+----+---------------+
| id | description |
+----+---------------+
| 3 | |
| 2 | another thing |
| 4 | last thing |
| 1 | stupid thing |
+----+---------------+
4 rows in set (0.00 sec)
The row with the empty space and id=3 should not be there. I understand that MySQL handles the NOT NULL directive this way by default, but I tried specifying the sql_mode option to "STRICT_ALL_TABLES", which I found to have the following affect:
Without sql_mode set:
mysql> drop table if exists table2;
Query OK, 0 rows affected (0.00 sec)
mysql> create table if not exists table2 (
-> id int not null auto_increment,
-> count int,
-> description varchar(45) not null,
-> primary key (`id`),
-> unique index `unique_desc` (`description`)
-> );
Query OK, 0 rows affected (0.02 sec)
mysql> insert into table2
-> (count,description)
-> values(12,"stupid thing");
Query OK, 1 row affected (0.00 sec)
mysql> insert into table2
-> (count)
-> values(5);
Query OK, 1 row affected, 1 warning (0.01 sec)
mysql> select * from table2;
+----+-------+--------------+
| id | count | description |
+----+-------+--------------+
| 1 | 12 | stupid thing |
| 2 | 5 | |
+----+-------+--------------+
2 rows in set (0.00 sec)
With sql_mode set to "STRICT_ALL_TABLES":
mysql> drop table if exists table1;
Query OK, 0 rows affected, 1 warning (0.03 sec)
mysql> drop table if exists table2;
Query OK, 0 rows affected (0.00 sec)
mysql> create table if not exists table2 (
-> id int not null auto_increment,
-> count int,
-> description varchar(45) not null,
-> primary key (`id`),
-> unique index `unique_desc` (`description`)
-> );
Query OK, 0 rows affected (0.02 sec)
mysql> insert into table2
-> (count,description)
-> values(12,"stupid thing");
Query OK, 1 row affected (0.01 sec)
mysql> insert into table2
-> (count)
-> values(5);
ERROR 1364 (HY000): Field 'description' doesn't have a default value
mysql> select * from table2;
+----+-------+--------------+
| id | count | description |
+----+-------+--------------+
| 1 | 12 | stupid thing |
+----+-------+--------------+
1 row in set (0.00 sec)
Note that in the above comparison, if you explicitly give the description field a NULL value, the database will properly complain WITH AND WITHOUT the "STRICT_ALL_TABLES" option set:
mysql> insert into table2
-> (count,description)
-> values(12,null);
ERROR 1048 (23000): Column 'description' cannot be null
Conclusion:
For some reason, setting the sql_mode affects this kind of insert, but does not affect the INSERT... SELECT behavior.
How can I get the data from table1 into table2 with a single query, and no empty cells?
Thanks in advance,
K
Simply use a WHERE clause:
insert ignore into table2(description)
select description from table1
where description <> '' and description is not null

Delete rows from one table in multiple databases?

I have multiple databases, and each of the databases have some tables in common. I'd like to do something like DELETE FROM *.table_name WHERE col_name LIKE 'value'; followed by OPTIMIZE TABLE *.table_name;
Is this possible with a single MYSQL query, or will I need to run these queries individually across each database?
If you have three databases with the table mytable, this might do it
DELETE A.*,B.*,C.*
FROM db1.mytable A,db2.mytable B,db3.mytable C
WHERE A.col_name LIKE 'value'
AND B.col_name LIKE 'value'
AND C.col_name LIKE 'value';
OPTIMIZE TABLE db1.mytable,db2.mytable,db3.mytable;
Give it a Try !!!
UPDATE 2013-05-31 18:27 EDT
I have a solution based on the INFORMATION_SCHEMA database and Dynamic SQL.
SOLUTION
USE db1
SET #GivenTable = 'mytb';
SET #GivenCol = 'dat';
SET #GivenValue = 'Burger King';
SET #x = 0;
SELECT GROUP_CONCAT(dbtb) INTO #OptimizeTableList
FROM (SELECT CONCAT(db,'.',tb) dbtb,CONCAT('dbalias',num) dbalias
FROM (SELECT table_schema db,table_name tb,(#x:=#X+1) num,column_name col
FROM information_schema.columns WHERE table_name=#GivenTable
and column_name=#GivenCol) AAA) AA;
SET #x = 0;
SELECT GROUP_CONCAT(dbalias,'.*') INTO #DeleteTableList
FROM (SELECT CONCAT(db,'.',tb) dbtb,CONCAT('dbalias',num) dbalias
FROM (SELECT table_schema db,table_name tb,(#x:=#X+1) num,column_name col
FROM information_schema.columns WHERE table_name=#GivenTable
and column_name=#GivenCol) AAA) AA;
SET #x = 0;
SELECT GROUP_CONCAT(dbtb,' AS ',dbalias) INTO #FromList
FROM (SELECT CONCAT(db,'.',tb) dbtb,CONCAT('dbalias',num) dbalias
FROM (SELECT table_schema db,table_name tb,(#x:=#X+1) num,column_name col
FROM information_schema.columns WHERE table_name=#GivenTable
and column_name=#GivenCol) AAA) AA;
SET #x = 0;
SELECT GROUP_CONCAT(CONCAT(dbalias,'.',col,'=',
QUOTE(#GivenValue)) SEPARATOR ' AND ') INTO #WhereClause
FROM (SELECT CONCAT(db,'.',tb) dbtb,CONCAT('dbalias',num) dbalias,col
FROM (SELECT table_schema db,table_name tb,(#x:=#X+1) num,column_name col
FROM information_schema.columns WHERE table_name=#GivenTable
and column_name=#GivenCol) AAA) AA;
SET #OptTableSQL = CONCAT('OPTIMIZE TABLE ',#OptimizeTableList);
SET #DeleteSQL = CONCAT('DELETE ',#DeleteTableList,' FROM ',#FromList,' WHERE ',#WhereClause);
PREPARE st FROM #DeleteSQL; EXECUTE st; DEALLOCATE PREPARE st;
PREPARE st FROM #OptTableSQL; EXECUTE st; DEALLOCATE PREPARE st;
SELECT * FROM db1.mytb;
SELECT * FROM db2.mytb;
SELECT * FROM db3.mytb;
SAMPLE DATA
DROP DATABASE IF EXISTS db1;
DROP DATABASE IF EXISTS db2;
DROP DATABASE IF EXISTS db3;
CREATE DATABASE db1;
CREATE DATABASE db2;
CREATE DATABASE db3;
CREATE TABLE db1.mytb
(id int not null auto_increment,
dat varchar(20),
primary key (id),key (dat));
INSERT INTO db1.mytb (dat) VALUES
('McDonald''s'),('Wendy''s'),
('Burger King'),('Jack in the Box');
CREATE TABLE db2.mytb LIKE db1.mytb;
CREATE TABLE db3.mytb LIKE db1.mytb;
INSERT INTO db2.mytb (dat) SELECT dat FROM db1.mytb;
INSERT INTO db3.mytb (dat) SELECT dat FROM db1.mytb;
SELECT * FROM db1.mytb;
SELECT * FROM db2.mytb;
SELECT * FROM db3.mytb;
SAMPLE DATA LOADED
mysql> DROP DATABASE IF EXISTS db1;
Query OK, 1 row affected (0.00 sec)
mysql> DROP DATABASE IF EXISTS db2;
Query OK, 1 row affected (0.00 sec)
mysql> DROP DATABASE IF EXISTS db3;
Query OK, 1 row affected (0.00 sec)
mysql> CREATE DATABASE db1;
Query OK, 1 row affected (0.00 sec)
mysql> CREATE DATABASE db2;
Query OK, 1 row affected (0.00 sec)
mysql> CREATE DATABASE db3;
Query OK, 1 row affected (0.00 sec)
mysql> CREATE TABLE db1.mytb
-> (id int not null auto_increment,
-> dat varchar(20),
-> primary key (id),key (dat));
Query OK, 0 rows affected (0.08 sec)
mysql> INSERT INTO db1.mytb (dat) VALUES
-> ('McDonald''s'),('Wendy''s'),
-> ('Burger King'),('Jack in the Box');
Query OK, 4 rows affected (0.00 sec)
Records: 4 Duplicates: 0 Warnings: 0
mysql> CREATE TABLE db2.mytb LIKE db1.mytb;
Query OK, 0 rows affected (0.06 sec)
mysql> CREATE TABLE db3.mytb LIKE db1.mytb;
Query OK, 0 rows affected (0.03 sec)
mysql> INSERT INTO db2.mytb (dat) SELECT dat FROM db1.mytb;
Query OK, 4 rows affected (0.00 sec)
Records: 4 Duplicates: 0 Warnings: 0
mysql> INSERT INTO db3.mytb (dat) SELECT dat FROM db1.mytb;
Query OK, 4 rows affected (0.00 sec)
Records: 4 Duplicates: 0 Warnings: 0
mysql> SELECT * FROM db1.mytb;
+----+-----------------+
| id | dat |
+----+-----------------+
| 1 | McDonald's |
| 2 | Wendy's |
| 3 | Burger King |
| 4 | Jack in the Box |
+----+-----------------+
4 rows in set (0.00 sec)
mysql> SELECT * FROM db2.mytb;
+----+-----------------+
| id | dat |
+----+-----------------+
| 1 | Burger King |
| 2 | Jack in the Box |
| 3 | McDonald's |
| 4 | Wendy's |
+----+-----------------+
4 rows in set (0.00 sec)
mysql> SELECT * FROM db3.mytb;
+----+-----------------+
| id | dat |
+----+-----------------+
| 1 | Burger King |
| 2 | Jack in the Box |
| 3 | McDonald's |
| 4 | Wendy's |
+----+-----------------+
4 rows in set (0.00 sec)
mysql>
SOLUTION EXECUTED
mysql> USE db1
Database changed
mysql> SET #GivenTable = 'mytb';
Query OK, 0 rows affected (0.00 sec)
mysql> SET #GivenCol = 'dat';
Query OK, 0 rows affected (0.00 sec)
mysql> SET #GivenValue = 'Burger King';
Query OK, 0 rows affected (0.00 sec)
mysql> SET #x = 0;
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT GROUP_CONCAT(dbtb) INTO #OptimizeTableList
-> FROM (SELECT CONCAT(db,'.',tb) dbtb,CONCAT('dbalias',num) dbalias
-> FROM (SELECT table_schema db,table_name tb,(#x:=#X+1) num,column_name col
-> FROM information_schema.columns WHERE table_name=#GivenTable
-> and column_name=#GivenCol) AAA) AA;
Query OK, 1 row affected (0.02 sec)
mysql> SET #x = 0;
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT GROUP_CONCAT(dbalias,'.*') INTO #DeleteTableList
-> FROM (SELECT CONCAT(db,'.',tb) dbtb,CONCAT('dbalias',num) dbalias
-> FROM (SELECT table_schema db,table_name tb,(#x:=#X+1) num,column_name col
-> FROM information_schema.columns WHERE table_name=#GivenTable
-> and column_name=#GivenCol) AAA) AA;
Query OK, 1 row affected (0.02 sec)
mysql> SET #x = 0;
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT GROUP_CONCAT(dbtb,' AS ',dbalias) INTO #FromList
-> FROM (SELECT CONCAT(db,'.',tb) dbtb,CONCAT('dbalias',num) dbalias
-> FROM (SELECT table_schema db,table_name tb,(#x:=#X+1) num,column_name col
-> FROM information_schema.columns WHERE table_name=#GivenTable
-> and column_name=#GivenCol) AAA) AA;
Query OK, 1 row affected (0.02 sec)
mysql> SET #x = 0;
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT GROUP_CONCAT(CONCAT(dbalias,'.',col,'=',
-> QUOTE(#GivenValue)) SEPARATOR ' AND ') INTO #WhereClause
-> FROM (SELECT CONCAT(db,'.',tb) dbtb,CONCAT('dbalias',num) dbalias,col
-> FROM (SELECT table_schema db,table_name tb,(#x:=#X+1) num,column_name col
-> FROM information_schema.columns WHERE table_name=#GivenTable
-> and column_name=#GivenCol) AAA) AA;
Query OK, 1 row affected (0.03 sec)
mysql> SET #OptTableSQL = CONCAT('OPTIMIZE TABLE ',#OptimizeTableList);
Query OK, 0 rows affected (0.00 sec)
mysql> SET #DeleteSQL = CONCAT('DELETE ',#DeleteTableList,' FROM ',#FromList,' WHERE ',#WhereClause);
Query OK, 0 rows affected (0.00 sec)
mysql> PREPARE st FROM #DeleteSQL; EXECUTE st; DEALLOCATE PREPARE st;
Query OK, 0 rows affected (0.00 sec)
Statement prepared
Query OK, 3 rows affected (0.00 sec)
Query OK, 0 rows affected (0.00 sec)
mysql> PREPARE st FROM #OptTableSQL; EXECUTE st; DEALLOCATE PREPARE st;
Query OK, 0 rows affected (0.00 sec)
Statement prepared
+----------+----------+----------+----------+
| Table | Op | Msg_type | Msg_text |
+----------+----------+----------+----------+
| db1.mytb | optimize | status | OK |
| db2.mytb | optimize | status | OK |
| db3.mytb | optimize | status | OK |
+----------+----------+----------+----------+
3 rows in set (0.05 sec)
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT * FROM db1.mytb;
+----+-----------------+
| id | dat |
+----+-----------------+
| 1 | McDonald's |
| 2 | Wendy's |
| 4 | Jack in the Box |
+----+-----------------+
3 rows in set (0.00 sec)
mysql> SELECT * FROM db2.mytb;
+----+-----------------+
| id | dat |
+----+-----------------+
| 2 | Jack in the Box |
| 3 | McDonald's |
| 4 | Wendy's |
+----+-----------------+
3 rows in set (0.01 sec)
mysql> SELECT * FROM db3.mytb;
+----+-----------------+
| id | dat |
+----+-----------------+
| 2 | Jack in the Box |
| 3 | McDonald's |
| 4 | Wendy's |
+----+-----------------+
3 rows in set (0.01 sec)
mysql>
WHAT DO THE QUERIES LOOK LIKE
mysql> SELECT #OptimizeTableList,#DeleteTableList,#FromList,
-> #WhereClause,#OptTableSQL,#DeleteSQL\G
*************************** 1. row ***************************
#OptimizeTableList: db1.mytb,db2.mytb,db3.mytb
#DeleteTableList: dbalias1.*,dbalias2.*,dbalias3.*
#FromList: db1.mytb AS dbalias1,db2.mytb AS dbalias2,db3.mytb AS dbalias3
#WhereClause: dbalias1.dat='Burger King' AND dbalias2.dat='Burger King' AND dbalias3.dat='Burger King'
#OptTableSQL: OPTIMIZE TABLE db1.mytb,db2.mytb,db3.mytb
#DeleteSQL: DELETE dbalias1.*,dbalias2.*,dbalias3.* FROM db1.mytb AS dbalias1,db2.mytb AS dbalias2,db3.mytb AS dbalias3 WHERE dbalias1.dat='Burger King' AND dbalias2.dat='Burger King' AND dbalias3.dat='Burger King'
1 row in set (0.00 sec)
mysql>
CAVEAT
You have to be standing in one of the three databases for it to work
Are you surprised it worked ??? Hey, so am I !!!
For more information on multiple-table DELETE, see the MySQL Documentation. Search for the phrase multiple-table DELETE statement.