2017-08-28 76 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