2013-10-10 75 views
0

我有這樣的查詢加入子查詢,而無需使用

SELECT DISTINCT 
    [fldID], 
    [fldValue] 
      FROM 
       (
        (
         SELECT 
          alias1.[fldID], 
          alias1.[fldValue] 
         FROM someT as alias1 
          .... 
        ) 
       ) AS subQuery_1 
      INNER JOIN 
      (
       SELECT 
        alias1.[fldID], 
        alias1.[fldValue] 
       FROM someT as alias1 
        ... 
      ) AS subQuery_2 USING(fldID, fldValue) 

它工作正常,在MySQL,但SQL Server不支持使用。所以,我必須使用JOIN這樣的:

ON [subQuery_1].[fldID] = [subQuery_2].[fldID] 
AND [subQuery_1].[fldValue] = [subQuery_2].[fldValue] 

但此查詢導致錯誤:

Ambiguous column name fldID 
Ambiguous column name fldValue 

所以,我怎麼能實現這樣一種在SQL Server JOIN的?

+3

你必須調整你的'SELECT'聲明說,不管你是從'subQuery_1'選擇或'subQuery_2' –

+0

向我們展示你想查詢在SQL Server上不起作用。向我們展示一個正在運行的MySQL查詢,然後說您對SQL Server進行了某種改變,但是它會引發錯誤,並不能幫助我們,因爲我們不再確切知道新的非工作查詢是什麼。這就是像這樣的語法錯誤的細節。 – RBarryYoung

+0

@RBarryYoung這個問題有一切需要。 – Szymon

回答

2

你只需要指定從哪個子查詢你把這些列從(這不要緊,你採取哪一種,你的情況,你在兩列加入)

SELECT DISTINCT 
subQuery_1.[fldID], 
subQuery_1.[fldValue] 
     FROM 
      (
       (
        SELECT 
         alias1.[fldID], 
         alias1.[fldValue] 
        FROM someT as alias1 
         .... 
       ) 
      ) AS subQuery_1 
     INNER JOIN 
     (
      SELECT 
       alias1.[fldID], 
       alias1.[fldValue] 
      FROM someT as alias1 
       ... 
     ) AS subQuery_2 
ON [subQuery_1].[fldID] = [subQuery_2].[fldID] 
AND [subQuery_1].[fldValue] = [subQuery_2].[fldValue] 
+1

謝謝!當然這是一個有效的解決方案! – kaa

0

在你查詢你是不是在最終選擇中添加表別名。您需要指定即將從表像這樣的列:

SELECT DISTINCT 
    subQuery_1.[fldID], 
    subQuery_1.[fldValue] 
      FROM 
       (
        (
         SELECT 
          alias1.[fldID], 
          alias1.[fldValue] 
         FROM someT as alias1 
          .... 
        ) 
       ) AS subQuery_1 
      INNER JOIN 
      (
       SELECT 
        alias1.[fldID], 
        alias1.[fldValue] 
       FROM someT as alias1 
        ... 
      ) AS subQuery_2 
      on [subQuery_1].[fldID] = [subQuery_2].[fldID] 
AND [subQuery_1].[fldValue] = [subQuery_2].[fldValue]