2017-08-28 37 views
1

大家好结果,MySQL的一个从2个表

我下表:

jobs_active:

| id | date_id | job_id | result | 
|-------------------------------------| 
| 1 | 2017-08-28 | 1  | failed | 
|-------------------------------------| 
| 2 | 2017-08-28 | 2  | failed | 
|_____________________________________| 

jobs_history:

| id | job_id | date_id | job_id | result | 
|----------------------------------------------| 
| 1 | 1  | 2017-08-27 | 1  | failed | 
|----------------------------------------------| 
| 2 | 1  | 2017-08-26 | 1  | success | 
|----------------------------------------------| 
| 3 | 2  | 2017-08-27 | 2  | failed | 
|----------------------------------------------| 
| 4 | 2  | 2017-08-26 | 2  | failed | 
|______________________________________________| 

而且我想得到这个结果:

       (2017-08-28)| (2017-08-27) | (2017-08-26) 


| id | date_id | job_id | result_now | result_lastDay1 | result_lastDay2 | 
|----------------------------------------------------------------------------| 
| 1 | 2017-08-27 | 1  | failed  | failed   | success   | 
|----------------------------------------------------------------------------| 
| 2 | 2017-08-26 | 2  | failed  | failed   | failed   | 
|____________________________________________________________________________| 

“result_lastDayN”列应该是动态的。这样我可以根据需要选择10个最后的日子。

我试过这个已经加入和联合,但我没有得到它的工作。 有没有人有一个想法,如果这是可能的?

+0

你基本上是在动态数据透视之后。 https://stackoverflow.com/questions/12598120/mysql-pivot-table-query-with-dynamic-columns – xQbert

回答

1

你有没有试过子查询?

select ja.*, 
(select result from jobs_history jh where job_id = ja.id and jh.date = j.date - INTERVAL 1 DAY) result_lastDay1, 
(select result from jobs_history jh where job_id = ja.id and jh.date = j.date - INTERVAL 2 DAY) result_lastDay2 
from 
jobs_active ja 
+0

谢谢,它工作:)我尝试了子查询我猜,但不是这样。 – SIMDesign