我是一名软件开发人员。我有一个问题:如何使用select和join访问多个表?
主表的名称如下:
logs_0215
logs_0315
logs_mmyy -> m = month; y = year
时间戳表的名称如下:
timestamp_0215
timestamp_0315
timestamp_mmyy -> m = month; y = year
我的查询仅适用于一个表格,如:
SELECT a.id, b.stamp, c.name AS portal, d.name AS company, e.name AS protocol, a.value
FROM logs_0315 AS a
LEFT JOIN timestamp_0315 AS b ON a.time_id = b.id
LEFT JOIN portale AS c ON a.portal_id = c.id
LEFT JOIN companies AS d ON a.comp_id = d.id
LEFT JOIN proocols AS e ON a.prot_id = e.id
WHERE b.stamp BETWEEN '2015-05-01' AND '2015-06-25'
如何访问包含logs_mmyy及其时间戳的所有表?
提前感谢您的帮助。
你诚挚的 t.koelpin
答案 0 :(得分:1)
您必须明确标识每个表格;必须在FROM
子句中按名称标识每个表。 SQL不支持标识符(表名,列名等)的通配符模式匹配。
根据您发布的内容,看起来您可以使用UNION ALL
集合运算符将多个SELECT语句的结果合并为一个查询:
SELECT a.id, ...
FROM logs_0315 a
LEFT JOIN timestamp_0315 AS b ON a.time_id = b.id
...
WHERE b.stamp BETWEEN '2015-05-01' AND '2015-06-25'
UNION ALL
SELECT a.id, ...
FROM logs_0415 a
LEFT JOIN timestamp_0415 AS b ON a.time_id = b.id
...
WHERE b.stamp BETWEEN '2015-05-01' AND '2015-06-25'
UNION ALL
SELECT a.id, ...
FROM logs_0515 a
LEFT JOIN timestamp_0515 AS b ON a.time_id = b.id
...
WHERE b.stamp BETWEEN '2015-05-01' AND '2015-06-25'
如果您需要对合并结果ORDER BY
,则可以将每个SELECT
语句括在parens中。像这样:
( SELECT a.id, ...
FROM logs_0315 a
LEFT JOIN timestamp_0315 AS b ON a.time_id = b.id
...
WHERE b.stamp BETWEEN '2015-05-01' AND '2015-06-25'
)
UNION ALL
( SELECT a.id, ...
FROM logs_0415 a
LEFT JOIN timestamp_0415 AS b ON a.time_id = b.id
...
WHERE b.stamp BETWEEN '2015-05-01' AND '2015-06-25'
)
UNION ALL
( SELECT a.id, ...
FROM logs_0515 a
LEFT JOIN timestamp_0515 AS b ON a.time_id = b.id
...
WHERE b.stamp BETWEEN '2015-05-01' AND '2015-06-25'
)
ORDER BY ...
为了使其动态化,要获取模式logs_mmyy
的所有表,您可以查询information_schema.tables
并获取表的列表,然后使用它来动态生成上述语句。此方法需要(至少)两个单独的SQL语句。在单个SQL语句中无法实现此类型的结果。