我有4张桌子可以轻松加入。最后一个连接需要两个列连接到类别表;其中,我想要在同一行中返回不同的值(categoryName)。
customerID,adID,categoryselectedID,providedcategoryID,categoryID,categoryName(这一个是正确的),wantedcategoryID,categoryID,categoryName(这个名称与提供的类别ID相同)
(mysql返回7条记录,除categoryName之外的所有信息对于提供和缺少都是相同的)
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都返回了14条记录7,因为它们提供了7个想要类别而不是只有7条记录在同一行上有不同的categoryName。)
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 :(得分: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
请注意,我已将offeredcategoryID
的联接查询条件从wantedcategoryID
更改为wantedcategory