2016-11-23 317 views
0

嗨需要一些幫助,MySQL查詢MySQL查詢優化

我的數據是,像這樣

Table base_status 

| id | order_id | status | dt_added | 
------------------------------------- 
| 1 | 123  | xyz | date3 | 
| 2 | 123  | abc | date2 | 
| 3 | 123  | pqr | date1 | 

我試圖讓輸出等

| order_id | xyz_date | abc_date | pqr_date | 
------------------------------------------- 
| 123  | date3 | date2 | date3 | 

MySQL查詢:

select BS.order_id, XYZ.dt_added AS xyz_date, 
     ABC.dt_added AS abc_date, PQR.dt_added AS pqr_date, 
from base_status BS 
LEFT JOIN base_status XYZ ON BS.order_id=TAS.order_id and TAS.status='xyz' 
LEFT JOIN base_status ABC ON BS.order_id=TAS.order_id and TAS.status='abc' 
LEFT JOIN base_status PQR ON BS.order_id=PQR.order_id and PQR.status='pqr' 
.... 

我的問題:如何避免3個左連接。只有一個連接有什麼可做的嗎?

回答

1

,最好的辦法不是多次查詢同一個表是用GROUP_CONCAT到組的三個日期,並FIELD保持一個掛單:

SELECT order_id, GROUP_CONCAT(dt_added) AS "xyz_date,abc_date,pqr_date " 
FROM base_status 
WHERE status IN ('xyz', 'abc', 'pqr') 
GROUP BY order_id 
ORDER BY FIELD(status, 'xyz', 'abc', 'pqr') 

當然,其結果將是SLI從你想達到什麼樣的ghtly不同:

| order_id | xyz_date,abc_date,pqr_date | 
----------------------------------------- 
| 123  | date3,date2,date1   | 
0

試試這個

SELECT 
    order_id, GROUP_CONCAT(status), GROUP_CONCAT(dt_added) 
FROM 
    base_status 
GROUP BY 
    order_id 

爲了得到輸出這樣

| order_id | status  | dt_added    | 
---------------------------------------------------- 
| 123  | xyz, abc, pqr | date3, date2, date1 | 
0

如果你有超過3個日期,動態支點是去

SELECT 
    GROUP_CONCAT(DISTINCT 
    CONCAT(
     'MAX(case when dt_added = ''', 
     dt_added , 
     ''' then dt_added end) AS ', 
     CONCAT(status,'_','date') 
    ) 
) INTO @sql 
from base_status; 

SET @sql = CONCAT('SELECT order_id, ', @sql, ' from base_status 
group by order_id'); 

PREPARE stmt FROM @sql; 
EXECUTE stmt; 
DEALLOCATE PREPARE stmt; 

FIDDLE

0

您可以使用都彙集功能與IF語句結合帶回列作爲你的方式註明: -

SELECT order_id, 
     MAX(IF(status = 'xyz', dt_added, NULL)) AS xyz_date, 
     MAX(IF(status = 'abc', dt_added, NULL)) AS abc_date, 
     MAX(IF(status = 'pqr', dt_added, NULL)) AS pqr_date 
FROM base_status 
GROUP BY order_id 

但是我懷疑,如果得到適當的索引的3表連接應該執行罰款。