mysql:组合表的列

时间:2016-03-22 13:43:11

标签: php mysql

我有这4张桌子

table FRUIT,  ID is Primary key

|     ID    |    code |    A   |    B      | 
--------------------------------------------
|     1     |    a01  |  apple1 |  quava1  |
|     2     |    a02  |  apple2 |  quava2  |


table FLOWER, ID is Primary key

|     ID    |    code |    C   |    D      | 
--------------------------------------------
|     1     |    a01  |  Rose1 |  Plumer1  |
|     2     |    a02  |  Rose2 |  Plumer2  |


table ANIMAL, ID is Primary key

|     ID    |    code |    E        |    F      | 
--------------------------------------------
|     1     |    a01  |  butterfly1 |  cat1     |
|     2     |    a02  |  butterfly2 |  cat2     |

table DAY, code is Primary key

|    code |    G    |     
-------------------------------------
|    a01  |  Monday |  
|    a02  |  Tuesday| 

我想调用并将这4个表组合成这样的

|  ID  |    A    |   B    |   C   |    D    |    E      |   F  |  G     |code  |
--------------------------------------------------------------------------------
|  1   |  apple1 | quava1 | Rose1 | Plumer1 |butterfly1 | cat1 |Monday  |a01   |
|  2   |  apple2 | quava2 | Rose2 | Plumer2 |butterfly2 | cat2 |Tuesday |a02   |

这是代码:

SELECT day*, fruit*, flower*, animal* 
       FROM day 
         LEFT JOIN fruit 
              ON day.code = fruit.code 
         LEFT JOIN flower 
              ON day.code = flower.code
          LEFT JOIN flower 
              ON day.code = animal.code
          ORDER BY day.code DESC;

据说列代码含糊不清。并且无法显示表格。 我需要帮助。我该如何解决这个问题?

3 个答案:

答案 0 :(得分:0)

您忘记在.column_name之间添加*,例如day.* 试试这个

   SELECT `day`.*, fruit.*, flower.*, animal.* 
           FROM `day` 
             LEFT JOIN fruit 
                  ON `day`.code = fruit.code 
             LEFT JOIN flower 
                  ON `day`.code = flower.code
              LEFT JOIN flower 
                  ON `day`.code = animal.code
              ORDER BY `day`.code DESC;

答案 1 :(得分:0)

除了你忘了一个点'。'在表名和*之间,这就是你从每个表中选择id和code列,你需要指定当有多个选项时你从哪里选择:

SELECT  fruit.A,fruit.B, flower.C,flower.D, animal.E,animal.F,day.G,day.code 
       FROM day 
         LEFT JOIN fruit 
              ON day.code = fruit.code 
         LEFT JOIN flower 
              ON day.code = flower.code
          LEFT JOIN animal
              ON day.code = animal.code
          ORDER BY day.code DESC;

答案 2 :(得分:0)

我会以这种方式执行此操作,使用AliasesJOINs加入所有表格(包括您忘记的animal表格),以及当然不要忘记在需要的地方包括句点.

SELECT fr.ID, fr.A, fr.B, fl.C, fl.D, a.E, a.F, d.G, fr.code
FROM `day` AS d
LEFT JOIN `fruit`  AS fr  ON d.code = fr.code 
LEFT JOIN `flower` AS fl  ON d.code = fl.code
LEFT JOIN `animal` AS a   ON d.code = a.code
ORDER BY d.code ASC;