查询以提取从不同表中插入/更新的所有行

时间:2015-07-21 09:57:59

标签: mysql vb.net

我写了一个更新mysql数据库的vb.net代码。

要检查代码是否正常工作,我在每个数据库表中添加了一个“Updated”字段,其中包含插入的时间戳(更新)。

我可以轻松地从每个表中提取更新的行,但我想知道是否可以只用一个查询提取所有更新的行。

请注意,表具有不同的字段和不同的字段数(因此我无法使用UNION)。

任何提示都表示赞赏。

2 个答案:

答案 0 :(得分:0)

所以前两个想法:
1)选择联盟
例如:

SELECT * FROM Table_name_1 
WHERE Updated > '20.07.2015'  
UNION  
SELECT * FROM Table_name_2 
WHERE Updated > '20.07.2015'  
UNION  
SELECT * FROM Table_name_3 
WHERE Updated > '20.07.2015'

2)如果你有200张表...最先进的,需要进行一些测试

SELECT DISTINCT TABLE_NAME 
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME IN ('Product')
AND TABLE_SCHEMA='YourDatabase';

你需要像这样创建一个光标

CREATE PROCEDURE curdemo()
   BEGIN
  DECLARE done INT DEFAULT FALSE;
  DECLARE a CHAR(16);
  DECLARE b, c INT;
  DECLARE cur1 CURSOR FOR SELECT id,data FROM test.t1;
  DECLARE cur2 CURSOR FOR SELECT i FROM test.t2;
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

  OPEN cur1;
  OPEN cur2;

  read_loop: LOOP
    FETCH cur1 INTO a, b;
    FETCH cur2 INTO c;
    IF done THEN
      LEAVE read_loop;
    END IF;
    IF b < c THEN
      INSERT INTO test.t3 VALUES (a,b);
    ELSE
      INSERT INTO test.t3 VALUES (a,c);
    END IF;
   END LOOP;

  CLOSE cur1;
  CLOSE cur2;
END;

玩得开心!和谷歌努力!

答案 1 :(得分:0)

确定测试这个fidlle:fiddle with 3 tables

CREATE TABLE table1
(`id` int, `productName` varchar(10), `Updated` datetime(6));
INSERT INTO table1  (`id`, `productName`, `Updated`)
VALUES
(1, 'OpenIM', '2015-07-21 13:58:01'),
(2, 'OpenAM', '2015-07-20 10:42:01'),
(3, 'OpenDJ', '2015-07-19 12:22:01')
;

CREATE TABLE table2
(`id` int, `productName` varchar(10), `Updated` datetime(6));
INSERT INTO table2  (`id`, `productName`, `Updated`)
VALUES
(1, 'OpenIMaa', '2015-07-21 21:58:01'),
(2, 'OpenAMbb', '2015-07-21 09:42:01'),
(3, 'OpenDJbb', '2015-07-20 07:22:01')
;

CREATE TABLE table3
(`id` int, `productName` varchar(10), `Updated` datetime(6));
INSERT INTO table3  (`id`, `productName`, `Updated`)
VALUES
(1, 'DDOpenIM', '2015-07-21 11:58:01'),
(2, 'FFOpenAM', '2015-07-21 10:42:01'),
(3, 'GGOpenDJ', '2015-07-19 12:22:01')
;

构建架构

 SELECT * FROM table1
 WHERE Updated >= subdate(current_date, 1)
 UNION
 SELECT * FROM table2
 WHERE Updated >= subdate(current_date, 1)
 UNION 
 SELECT * FROM table3
 WHERE Updated >= subdate(current_date, 1);

执行SQL

 | id | productName |                Updated |
 |----|-------------|------------------------|
 |  1 |      OpenIM | July, 21 2015 13:58:01 |
 |  2 |      OpenAM | July, 20 2015 10:42:01 |
 |  1 |    OpenIMaa | July, 21 2015 21:58:01 |
 |  2 |    OpenAMbb | July, 21 2015 09:42:01 |
 |  3 |    OpenDJbb | July, 20 2015 07:22:01 |
 |  1 |    DDOpenIM | July, 21 2015 11:58:01 |
 |  2 |    FFOpenAM | July, 21 2015 10:42:01 |

玩得开心!