[英]MySQL select one record from multiple tables
I have 400+ tables and each has a column timestamp. 我有400多个表,每个表都有列时间戳。 I'd like to pull the first row/record for timestamp for each of these tables. 我想为这些表中的每一个拉时间戳的第一行/记录。 I don't want to run 400+ queries, what would the best way to do this be? 我不想运行400多个查询,最好的方法是什么?
You can run a UNION query like this: 您可以这样运行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
Use a loop to create this statement: 使用循环创建此语句:
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;
The need for the first record from 400+ tables smells like poor design, but if they have the same schema, you can use UNION ALL
: 需要从400多个表中获得第一条记录看起来有点糟糕的设计,但是如果它们具有相同的架构,则可以使用UNION ALL
:
SELECT * FROM foo ORDER BY timestamp ASC LIMIT 1
UNION ALL
SELECT * FROM bar ORDER BY timestamp ASC LIMIT 1
UNION ALL
SELECT * FROM baz ORDER BY timestamp ASC LIMIT 1
-- etc...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.