3

我有 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_id 取回 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   | 
    ----------------------------------------------------
4

3 回答 3

5

就像是?

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 
于 2013-07-10T11:51:56.477 回答
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 
于 2013-07-10T11:57:49.940 回答
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 关系!

于 2013-07-10T11:58:29.613 回答