重命名内部联接中的列名称

时间:2013-07-10 11:48:27

标签: php mysql join inner-join

我有2张这样的表:

Table 'c'

|  id  |  item_1  |   item_2  |
-------------------------------
|  1   |   1      |    2      |
-------------------------------

Table 'i'

|  id  |  name    | 
-------------------
|  1   |   item   |   
-------------------
|  2   |  item_2  |
-------------------

不,我需要从表c得到结果包括项目的名称。所以我为此建立了一个内部联接。

SELECT c.*, i.name FROM c 

INNER JOIN i ON 
c.item_1 = i.id 
OR 
c.item_2 = i.id 

这很好用。但我得到这样的回复:

   |  id  |  item_1  |   item_2  |  name   |
    ----------------------------------------
    |  1   |   1      |    2      | item_2 |
    ----------------------------------------

问题很清楚 - 我需要找回两个item_ids的2个名字,但只能得到一个。那么可以为列设置新名称吗?像这样的东西:

SELECT c.*, i.name FROM c 

INNER JOIN i ON 
c.item_1 = i.id SET name AS name_1
INNER JOIN i ON 
c.item_2 = i.id SET name AS name_2

所以结果将是这样的:

   |  id  |  item_1  |   item_2  |  name_1   |  name_2 |
    ----------------------------------------------------
    |  1   |   1      |    2      | item_1 |  item_2   | 
    ----------------------------------------------------

3 个答案:

答案 0 :(得分:3)

喜欢什么?

SELECT c.*, 
       i1.name as name_1, 
       i2.name as name_2
  FROM c 
  INNER JOIN I as i1 
     ON c.item_1 = i1.id 
  INNER JOIN I as i2 
     ON c.item_2 = i2.id 

答案 1 :(得分:1)

这是相同的

SELECT c.*, 
       i1.name as name_1, 
       i1.name as name_2
  FROM c 
  INNER JOIN I as i1 
     ON c.item_1 = i1.id 

答案 2 :(得分:1)

尽管你的桌面设计很漂亮,但你可以使用别名多次加入一个表。

SELECT c.*, 
       i1.name as name1, 
       i2.name as name2 
FROM (c INNER JOIN i AS i1 ON c.item1=i1.id_i) 
     INNER join i as i2 ON c.item2=i2.id_i

但请重新考虑桌面设计,这是c和i之间简单的1:n关系!