2017-05-11 72 views
1

我想使用表的列值作爲列名,並將它用作與另一個表列名的JOIN ON值。以下是我的查詢。在列值上使用Mysql JOIN作爲列名與另一個表列名

SELECT nid, sid, 
     MAX(CASE WHEN cid = 2 THEN data END) first_name, 
     MAX(CASE WHEN cid = 3 THEN data END) last_name, 
     MAX(CASE WHEN cid = 4 THEN data END) email, 
     MAX(CASE WHEN cid = 5 THEN data END) phone_number, 
     MAX(CASE WHEN cid = 6 THEN data END) transitions, 
     MAX(CASE WHEN cid = 7 THEN data END) **upload**, 
     MAX(CASE WHEN cid = 9 THEN data END) coupon_code 
    FROM wsd AS wsd JOIN files AS fm ON **upload** = fm.fid WHERE nid IN(66,67) GROUP BY sid 

正如你看到上面的代碼,我想使用上傳列作爲JOIN在另一個表上。另外,是否可以在結果中嵌入HTML標籤?

+0

你應該看看查詢執行的,以獲得知道你爲什麼不能引用在你們這樣的查詢聯接子句別名。 https://sqlbolt.com/lesson/select_queries_order_of_execution – Ognj3n

+0

這個問題似乎分成兩部分。如果是這樣,我不明白第一部分。 – Strawberry

+0

你可以發佈表結構和一些插入查詢來獲得一些測試數據嗎?乾杯 – chickenchilli

回答

0

我試圖用臨時表得到結果。這是我的答案。

CREATE TEMPORARY TABLE IF NOT EXISTS my_temp_table SELECT sid, cid, data FROM wsd WHERE cid = 7 AND nid IN (66,67); 
SELECT wsd.nid, wsd.sid, fm.filename, 
     MAX(CASE WHEN wsd.cid = 2 THEN wsd.data END) fn, 
     MAX(CASE WHEN wsd.cid = 3 THEN wsd.data END) ln, 
     MAX(CASE WHEN wsd.cid = 4 THEN wsd.data END) email, 
     MAX(CASE WHEN wsd.cid = 5 THEN wsd.data END) ph, 
     MAX(CASE WHEN wsd.cid = 6 THEN wsd.data END) tr, 
     MAX(CASE WHEN wsd.cid = 7 THEN wsd.data END) upr, 
     MAX(CASE WHEN wsd.cid = 9 THEN wsd.data END) coc 
    FROM wsd wsd JOIN my_temp_table ON wsd.sid = my_temp_table.sid JOIN files fm ON my_temp_table.data = fm.fid WHERE nid IN(66,67) GROUP BY wsd.sid; 

代替臨時表的,更好的查詢,如下所示:

SELECT wsd.nid, wsd.sid, fm.filename, 
      MAX(CASE WHEN wsd.cid = 2 THEN wsd.data END) fn, 
      MAX(CASE WHEN wsd.cid = 3 THEN wsd.data END) ln, 
      MAX(CASE WHEN wsd.cid = 4 THEN wsd.data END) email, 
      MAX(CASE WHEN wsd.cid = 5 THEN wsd.data END) ph, 
      MAX(CASE WHEN wsd.cid = 6 THEN wsd.data END) tr, 
      MAX(CASE WHEN wsd.cid = 7 THEN wsd.data END) upr, 
      MAX(CASE WHEN wsd.cid = 9 THEN wsd.data END) coc 
     FROM wsd wsd LEFT JOIN files fm ON wsd.data = fm.fid WHERE nid IN(66,67) GROUP BY wsd.sid; 
相關問題