0
私は簡単に結合できる4つの表があります。最後の結合では、カテゴリテーブルに2つのカラムを結合する必要があります。同じ行に別の値(categoryName)が返されます。2つの列を1つの表から1つの列に結合すると、2つの列ごとに異なる結果または同じ結果が返される
出力
顧客ID、ADID、categoryselectedID、offeredcategoryID、カテゴリID、カテゴリ名(これが正しい)、wantedcategoryID、カテゴリID、カテゴリ名(この1つはofferedcategoryIDと同じ名前を表示)
テーブルを所望と列
- 顧客:得意先(PK)
- 広告:ADID(PK)、得意先(FK)
- はcategoriesselected:categoryselectedID(PK)、ADID(FK)、offeredcategoryID(FK)、wantedcategoryID(FK)
- カテゴリ:カテゴリID(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
(私はまた、すべての両方が上の異なる区分名を持つ唯一の7のレコードであることとは対照的に、カテゴリを望むために7を提供するために14のレコードの7を返しUNIONとUNIONを試してみました同じ行)
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
あなたの質問のために
wantedcategoryID
にofferedcategoryID
から参加した検索条件を変更し注意、不明であるあなたは、あなたの問題が何であるかを言い換えることができますか?そして、あなたのテーブルの情報形式を変更してください、それは読みにくいです。 – Eduard
変更を参照してください –
2番目のクエリでは、 'Category'列の最初のクエリのすべてのレコードが' Offered Category'であることを明示的に述べたので、2番目のクエリは実際に14行を返します。 「募集カテゴリー」になります。 – Eduard