2016-04-14 18 views
0

我有表 '文章'如何從兩個表格中進行選擇?

 
+-------------+ 
| articles | 
+----+--------+ 
| id | title | 
+----+--------+ 
| 1 | title1 | 
+----+--------+ 
| 2 | title2 | 
+----+--------+ 
| 3 | title3 | 
+----+--------+ 

表 '目錄'

 
+---------------------+ 
|  catalogue  | 
+----+--------+-------+ 
| id | group | name | 
+----+--------+-------+ 
| 1 | group1 | name1 | 
+----+--------+-------+ 
| 2 | group1 | name2 | 
+----+--------+-------+ 
| 3 | group2 | name3 | 
+----+--------+-------+ 
| 4 | group2 | name4 | 
+----+--------+-------+ 

綁定表 'bindTable'

 
+------------+--------------+-------+ 
|    bindTable   | 
+------------+--------------+-------+ 
| id_article | id_catalogue | value | 
+------------+--------------+-------+ 
|  1  |  2  | 1 | 
+------------+--------------+-------+ 
|  1  |  3  | 4 | 
+------------+--------------+-------+ 
|  3  |  1  | 2 | 
+------------+--------------+-------+ 
|  3  |  3  | 1 | 
+------------+--------------+-------+ 
|  3  |  4  | 3 | 
+------------+--------------+-------+ 

和我需要得到結果如表 '結果' ,在那裏我可以得到配對「catalogue_name:價值」從表'文章'的選定項目

 
+-----------------------------------------------------+ 
|      result      | 
+------------+---------------+----------------+-------+ 
| article_id | article_title | catalogue_name | value | 
+------------+---------------+----------------+-------+ 
|  1  |  title1 | group1_name2, | 1 | 
|   |    | group2_name3 | 4 | 
+------------+---------------+----------------+-------+ 
|  3  |  title3 | group1_name1, | 2 | 
|   |    | group2_name3, | 1 | 
|   |    | group2_name4 | 3 | 
+------------+---------------+----------------+-------+ 

任何人都可以告訴我一個查詢字符串與一個數據庫查詢?感謝您的關注。

 
My vision: 
    SELECT b.id_article, a.title, c.group, c.name, b.value 
    FROM bindTable b 
    JOIN articles a ON a.id = b.id_articles 
    JOIN catalogue c ON c.id = b.id_catalogue 
    WHERE b.id_article = 1 

,但我需要一個一行對c.name & b.value一個a.id

+0

值'''也像'catalogue_name'一樣是'concat'? –

+0

沒關係,只有名字 – Alaksander

+0

你試過什麼查詢?你學會了如何做JOIN?當慾望輸出不清晰時, – user3741598

回答

0

一個選擇與內部聯接

select a.article_id, a.article_title, b.catalogue_name, b.value 
from bindTable as c 
inner join articles as a on a.id = c. article_id 
inner join catalogues as b on c. id_catalogue = b.id 
0

這應該這樣做。

SELECT articles.id AS article_id, 
     articles.title AS article_title, 
     CONCAT_WS('_', catalogue.group, catalogue.name) AS catalogue_name, 
     bindTable.value AS value 
FROM bindTable 
    INNER JOIN articles ON bindTable.id_article = articles.id 
    INNER JOIN catalogue ON bindTable.id_catalogue = catalogue.id 
+1

我不認爲你需要一個'LEFT JOIN'一個簡單的'INNER JOIN'應該可以工作 –

+0

確實如此,感謝評論我會更新我的答案。 –

+0

對不起我的英語,我從'文章'的'標題'搜索,我需要添加到結果表相應的字段標題ID從表目錄和它的價值與綁定表,例如,從文章title1我得到兩個重疊字段從表'綁定'與id'1',並且值'1'和'4'。在表'目錄'中找到id我得到它的名字:「group1 name2」&「group2 name3」。最後我需要'title1'| 「group1 name2 = 1」| 「group2 name3 = 4」 – Alaksander

相關問題