2017-08-04 90 views
0

我想從兩個表中選擇一些數據,但它比我第一次想到的稍微複雜一些。我有兩張桌子(content & relations)。從關係表加入MySQL

content 
    +----+-----------+--------------------+--------------+ 
    | id | elementId |  title  | field_body | 
    +----+-----------+--------------------+--------------+ 
    | 1 |   1 | test title   | test body | 
    | 2 |   2 | another title  | another body | 
    | 3 |   3 | category 10  | null   | 
    | 4 |   4 | sub category 20 | null   | 
    +----+-----------+--------------------+--------------+ 


    relations 
    +----+----------+----------+-----------+ 
    | id | sourceId | targetId | sortOrder | 
    +----+----------+----------+-----------+ 
    | 1 |  2 |  3 |   1 | 
    | 2 |  2 |  4 |   2 | 
    +----+----------+----------+-----------+ 

的方式表是設置如下, 我創建我的網站的「物品」是由以下部分組成:

  • 文章標題
  • 文章正文
  • 文章主類
  • 文章子類別

我需要獲取每一篇文章,並從表content

因此,例如,它會帶回該行相關的主副類別 - >

another title, another body, category10, sub category 20

因爲在關係表源id爲2,鏈接到文章的elementId,targetId是與文章關聯的類別的ID。

解決此問題的最佳方法是什麼?我已經嘗試了幾種不同的查詢的得到這個工作,但它似乎並不可能

+2

提示:'JOIN' ...... –

+0

哪裏是你試圖查詢股吧 – Bhargav

+1

我不會像設計表首先。它非常混亂,如果它變得更大,你會遇到問題。爲什麼你不會有一個名爲Categories的表,其中包含不同類別的類別。您可以通過在文章表中將該類別的FK關聯到每個文章所屬的類別。 – GarRudo

回答

0

我認爲這是一個錯誤的烏爾關係表中的數據,這可能是基於鄰接表型號:

ID爲== 2記錄必須具有的sourceID場== 3:

relations 
    +----+----------+----------+-----------+ 
    | id | sourceId | targetId | sortOrder | 
    +----+----------+----------+-----------+ 
    | 1 |  2 |  3 |   1 | 
    | 2 |  3 |  4 |   2 | 
    +----+----------+----------+-----------+ 

之後ü可以試試這個SQL:

select 
c.id, 
c.title as article_title, 
c.field_body as article_body, 
c1.title as article_main_category, 
c2.title as article_sub_category 
from 
content c 
join relations as r1 on r1.sourceId = c.elementId 
join content as c1 on c1.elementId = r1.targetId 
join relations as r2 on r2.sourceId = c1.elementId 
join content as c2 on c2.elementId = r2.targetId 

如果r elations表數據是確定的,而且中將sortOrder場是有道理的,那麼我們可以試試這個SQL查詢:

select 
c.id, 
c.title as article_title, 
c.field_body as article_body, 
c1.title as article_main_category, 
c2.title as article_sub_category 
from 
content c 
join relations as r1 on r1.sourceId = c.elementId and r1.sortOrder = 1 
join content as c1 on c1.elementId = r1.targetId 
join relations as r2 on r2.sourceId = c.elementId and r2.sortOrder = 2 
join content as c2 on c2.elementId = r2.targetId 
+0

sourceId是與該類別關聯的文章的elementId,因爲每個文章都有一個「主類別」和「子類別」,主類別是具有sortOrder == 1的項目,子類別是該項目sortOrder == 2如果有意義的話? – scriptss

+0

我剛剛更新了我的文章,希望它會有所幫助。 –

+0

第二個查詢似乎工作完美,謝謝! – scriptss