【发布时间】:2010-11-02 14:55:33
【问题描述】:
我尝试使用临时表作为 SELECT 语句的中间结果持有者。问题是我无法在其他查询语句中多次访问临时表,我希望这是可能的,即使临时表无用。
MySql 中是否有替代临时表的方法,可以让我提取我的 SQL 语句。
我不能使用存储过程(不能从公司使用的网络框架版本访问它们),我不想使用光标。
编辑:
我的代码看起来有点像这样:
创建临时表:
CREATE TEMPORARY TABLE dates_with_entries (
seq INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
datum VARCHAR(32)
);
INSERT INTO dates_with_entries (datum) SELECT datum AS Datum from project_times
WHERE user_id = 20 GROUP BY datum ORDER BY datum desc LIMIT 13;
然后我使用临时表的代码看起来有点像这样(我把它简化为我遇到的问题......)
SELECT
...
FROM (SELECT entrie_date AS datum FROM dates_with_entries ) AS sub_result
INNER JOIN project_times
ON sub_result.datum = project_times.datum AND project_times.user_id = 20
LEFT JOIN works AS w ON project_times.work_id = w.id
LEFT JOIN sub_projects AS sp ON sp.id = w.sub_project_id
LEFT JOIN projects AS p ON p.id = sp.project_id
GROUP BY datum
UNION(
SELECT
..
FROM (SELECT entrie_date AS datum FROM dates_with_entries ) AS sub_result
INNER JOIN project_times AS pt ON pt.datum = sub_result.datum
INNER JOIN works AS w on w.id = pt.work_id
INNER JOIN sub_projects AS sp on w.sub_project_id = sp.id
INNER JOIN projects AS p ON sp.project_id = p.id
WHERE pt.user_id = 20
);
后面的数字会被ruby代替,这只是为了测试SQL语句。
【问题讨论】:
-
展示一些关于如何创建和使用临时表的示例 SQL。
标签: mysql temp-tables