MySQL从多个表中选择一条记录

时间:2017-01-17 17:48:49

标签: mysql multiple-tables records

我有400多个表,每个表都有一个列时间戳。我想拉出每个表的时间戳的第一行/记录。我不想运行400多个查询,最好的方法是什么?

2 个答案:

答案 0 :(得分:1)

您可以像这样运行 UNION 查询:

SELECT Id, yourColumn, timestamp FROM Table001 ORDER BY timestamp DESC LIMIT 1
UNION ALL
SELECT Id, yourColumn, timestamp FROM Table002 ORDER BY timestamp DESC LIMIT 1
UNION ALL
SELECT Id, yourColumn, timestamp FROM Table003 ORDER BY timestamp DESC LIMIT 1
ORDER BY timestamp 

使用循环创建此语句:

SET @resultQuery = NULL;
SELECT
  GROUP_CONCAT(
    DISTINCT
    CONCAT('SELECT * FROM ', table_name, ' ORDER BY timestamp DESC LIMIT 1 ')
    SEPARATOR '\r\nUNION\r\n'
  )
INTO
  @resultQuery
FROM
  information_schema.COLUMNS
WHERE
  table_schema = '???' AND column_name LIKE '%timestamp';

SELECT @resultQuery;

答案 1 :(得分:1)

对400多个表中第一条记录的需求闻起来很糟糕,但如果它们具有相同的模式,则可以使用$('#calendar').fullCalendar( 'rerenderEvents' );

UNION ALL