Mysql 将一个表中的两列连接到另一个表中的一列,为这两列中的每一列返回不同或相同的结果
我有4个表,我可以很容易地加入。最后一个联接需要将两列联接到一个categories表;我希望在同一行中返回不同的值(categoryName)Mysql 将一个表中的两列连接到另一个表中的一列,为这两列中的每一列返回不同或相同的结果,mysql,join,unions,aliases,Mysql,Join,Unions,Aliases,我有4个表,我可以很容易地加入。最后一个联接需要将两列联接到一个categories表;我希望在同一行中返回不同的值(categoryName) SELECT customers.*, ads.*, categoriesselected.categoryselectedID, categoriesselected.offeredcategoryID, categories.categoryID, categories.categoryName, 'Offered Category' AS Ca
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
期望输出
customerID、adID、categoryselectedID、offeredcategoryID、categoryID、categoryName(此项正确)、wantedcategoryID、categoryID、categoryName(此项显示与offeredcategoryID相同的名称)
表和列
如果我没有弄错的话,问题在于最后一个连接,它给了您一个不正确的输出
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
请注意,我已将
wantedcategory
的联接查询条件从offeredcategoryID
更改为wantedcategoryID
,wantedcategory您的问题不清楚,能否重新表述您的问题?请修改您的表信息格式,因为它很难读取。请参见更改。第二次查询确实会产生14行,因为您明确指出,在第二次查询中,类别
列下第一次查询的所有记录都是提供的类别
,Category
将是Wanted Category
。如果您可以绘制样本数据以及当前输出与预期输出的对比,那么我很乐意帮助您进行查询。
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