2017-05-03 64 views
0

我有4個表格,我可以輕鬆加入。最後一次連接需要將兩列連接到類別表;其中,我想要在同一行中返回一個不同的值(categoryName)。將兩列從一個表連接到另一列,其他返回不同或相同的結果,用於每列的兩列

輸出所需

的customerID,ADID,categoryselectedID,offeredcategoryID,的categoryID,類別名稱(這是正確的),wantedcategoryID,的categoryID,類別名稱(這一個顯示相同的名稱offeredcategoryID)

表和列

  1. 客戶:的customerID(PK)
  2. 廣告:ADID(PK)的customerID(FK)
  3. categoriesselected:categoryselectedID(PK),ADID(FK),offeredcategoryID(FK),wantedcategoryID(FK)
  4. 類:的categoryID(PK),類別名稱

(MySQL的返回7次的記錄和除類別名稱的所有信息是上是相同的產品,並希望)

SELECT customers.*, ads.*, categoriesselected.categoryselectedID, categoriesselected.offeredcategoryID, offeredcategory.categoryID, offeredcategory.categoryName, categoriesselected.wantedcategoryID, wantedcategory.categoryID, wantedcategory.categoryName 

FROM customers 
    INNER JOIN ads ON ads.customerId = customers.customerID 
    INNER JOIN categoriesselected ON categoriesselected.adID = ads.adID 
    LEFT OUTER JOIN categories AS offeredcategory ON offeredcategory.categoryID = categoriesselected.offeredcategoryID 
    LEFT OUTER JOIN categories AS wantedcategory ON wantedcategory.categoryID = categoriesselected.offeredcategoryID 

(我也嘗試了UNION和UNION ALL都返回14條記錄7爲想要的類別,而不是僅爲7條不同的類別名稱上提供的7同一排)。

SELECT customers.*, ads.*, categoriesselected.categoryselectedID, categoriesselected.offeredcategoryID, categories.categoryID, categories.categoryName, 'Offered Category' AS Category 
FROM customers 
    JOIN ads ON ads.customerId = customers.customerID 
    JOIN categoriesselected ON categoriesselected.adID = ads.adID 
    JOIN categories ON categories.categoryID = categoriesselected.offeredcategoryID 

UNION ALL 

SELECT customers.*, ads.*, categoriesselected.categoryselectedID, categoriesselected.wantedcategoryID, categories.categoryID, categories.categoryName, 'Wanted Category' AS Category 
FROM customers 
    JOIN ads ON ads.customerId = customers.customerID 
    JOIN categoriesselected ON categoriesselected.adID = ads.adID 
    JOIN categories ON categories.categoryID = categoriesselected.wantedcategoryID 
+0

你的問題不清楚,你可以改一下你的問題是什麼?並且請修改你的表格信息格式,這很難閱讀。 – Eduard

+0

請查看變更 –

+0

那麼第二個查詢確實會產生14行,因爲您明確指出,「Category」列下的第一個查詢的所有記錄都是「Offered Category」,而在第二個查詢中,「Category」會被要求分類。 – Eduard

回答

0

如果我沒有弄錯,問題在於最後的連接,這會給你一個錯誤的輸出。

SELECT customers.*, ads.*, categoriesselected.categoryselectedID, 
    categoriesselected.offeredcategoryID, offeredcategory.categoryID, offeredcategory.categoryName, 
    categoriesselected.wantedcategoryID, wantedcategory.categoryID, wantedcategory.categoryName 
FROM customers 
    INNER JOIN ads ON ads.customerId = customers.customerID 
    INNER JOIN categoriesselected ON categoriesselected.adID = ads.adID 
    LEFT OUTER JOIN categories AS offeredcategory ON offeredcategory.categoryID = categoriesselected.offeredcategoryID 
    LEFT OUTER JOIN categories AS wantedcategory ON wantedcategory.categoryID = categoriesselected.wantedcategoryID 

注意,我改變了聯接查詢條件從offeredcategoryIDwantedcategoryIDwantedcategory

相關問題