用于以行方式显示行的MySql查询

时间:2017-03-10 13:20:05

标签: mysql sql

我要连接三个表,结果输出将是这样的

+---------------+--------------+-------------+-------------+
| Category_Name | English      | French      | German      |
+---------------+--------------+-------------+-------------+
| Clothing      | english_name | french_name | german_name |
| Electronics   | NULL         | NULL        | NULL        |
| Ornaments     | NULL         | NULL        | NULL        |
+---------------+--------------+-------------+-------------+

以下是我的table_structure

tbl_category
+----+---------------+
| id | category_name |
+----+---------------+
| 1  | Clothing      |
| 2  | Electronics   |
| 3  | Ornaments     |
+----+---------------+

tbl_languages
+----+----------+
| id | language |
+----+----------+
| 1  | English  |
| 2  | French   |
| 3  | German   |
+----+----------+

tbl_languages_data

+----+-------------+-------------+---------------+
| id | language_id | category_id | category_name |
+----+-------------+-------------+---------------+
| 1  | 1           | 1           | english_name  |
| 2  | 2           | 1           | french_name   |
| 3  | 3           | 1           | german_name   |
+----+-------------+-------------+---------------+

我有两个问题。 1.这些关系是否有效,或者可以采用其他方法来避免死锁 2.获得此结果的查询是什么。

注意:输出应该动态,因为我要向tbl_language添加更多数据。

2 个答案:

答案 0 :(得分:0)

应该是:

SELECT Category_Name
        MAX(CASE when lan.language_id = 1 THEN lan.category_name END) as 'English',
        MAX(CASE when lan.language_id = 2 THEN lan.category_name END) as 'French',
        MAX(CASE when lan.language_id = 3 THEN lan.category_name END) as 'German'
FROM tbl_category cat
RIGHT JOIN tbl_languages_data lan ON cat.id = lan.category_id
GROUP BY Category_Name

注意:没有注意到您的编辑,我认为您无法动态地将列添加到预期结果中。如果我错了,请有人纠正我。

答案 1 :(得分:-1)

我会从 tbl_languages_data 中省略最后一列类别名称。并将Language_id作为数字引用,这样您将比较具有相同数据类型的两个索引( int int )。这将比带有 int 字符串更快。这将导致以下查询:

SELECT  cat.category_name
,       lang.language
FROM    tbl_category AS cat
LEFT JOIN tbl_languages_data AS lang_data
        ON lang_data.category_id = cat.id
LEFT JOIN tbl_languages AS lang
        ON lang_data.language_id = lang.id

请注意,这与预期结果集不同。这三种语言现在被翻译成一列。这是你的桌子设计:

 tbl_category
+----+---------------+
| id | category_name |
+----+---------------+
| 1  | Clothing      |
+----+---------------+
| 2  | Electronics   |
+----+---------------+
| 3  | Ornaments     |
+----+---------------+

tbl_languages
+----+----------+
| id | language |
+----+----------+
| 1  | English  |
+----+----------+
| 2  | French   |
+----+----------+
| 3  | German   |
+----+----------+

tbl_languages_data

+----+-------------+-------------+
| id | language_id | category_id | 
+----+-------------+-------------+
| 1  | 1           | 1           | 
+----+-------------+-------------+
| 2  | 2           | 1           | 
+----+-------------+-------------+
| 3  | 3           | 1           | 
+----+-------------+-------------+