内部连接相同的值表

时间:2014-07-17 10:55:05

标签: mysql sql left-join inner-join

我的表格条目如下。对象id是相同的。我需要获取对象id的另一个值,该值具有该特定object_id的“HR”/“Infra”。

--------------------------------------------------
|id     | field_id  | object_id     | value_text
----------------------------------------------------    
|182    |   11      | 149           | HR
|183    |   13      | 149           | Learning Management   
|184    |   11      | 150           | HR 
|185    |   13      | 150           | Compensation & Benefits   
|186    |   11      | 151           | HR 
|187    |   13      | 151           | Leave Management  
|188    |   11      | 152           | HR 
|189    |   13      | 152           | Compensation & Benefits   
|190    |   11      | 153           | Infra 
|191    |   13      | 153           | Hardisk   
|192    |   11      | 154           | Infra 
|193    |   13      | 154           | Software  
|194    |   11      | 155           | Infra
|195    |   13      | 155           | Network   
|196    |   11      | 156           | HR 
|197    |   13      | 156           | Position Management   
|198    |   11      | 139           | HR 
|199    |   13      | 139           | Compensation & Benefits   
|200    |   11      | 157           | Infra 
|201    |   13      | 157           | Network       

查询:

SELECT d.value_text 
FROM dynamic d 
INNER JOIN dynamic dv ON d.object_id = d.object_id AND d.field_id = "13" 
                     AND dv.field_id = "11" AND dv.value_text = "HR"

需要输出:

--------------
| value_text |
--------------
| Learning Management 
| Compensation & Benefits
| Position Management

第二次查询:

SELECT d.value_text 
FROM dynamic d 
INNER JOIN dynamic dv ON d.object_id = d.object_id AND d.field_id = "13" 
                     AND dv.field_id = "11" AND dv.value_text = "Infra"

需要输出:

--------------
| value_text |
--------------
| Network 
| Software
| Hardisk

如何修改查询以获取详细信息。

2 个答案:

答案 0 :(得分:0)

您希望将两个查询合并在一起吗?

然后你可以这样做:

SELECT d.value_text FROM dynamic d 
INNER JOIN dynamic dv ON d.object_id = d.object_id AND
d.field_id = "13" AND dv.field_id = "11" 
AND (dv._obejct_id = "Infra" OR dv._obejct_id = "HR")

我希望这就是你所需要的。

答案 1 :(得分:0)

不确定你要求的是什么,但试试这些:

select
      dv.id, dv.field_id, dv.object_id, dv.value_text
from dynamic d
inner join dynamic dv on dv.field_id = 13 and d.object_id = dv.object_id
where d.field_id = 11
and d.value_text = 'HR'
;

select
      dv.id, dv.field_id, dv.object_id, dv.value_text
from dynamic d
inner join dynamic dv on dv.field_id = 13 and d.object_id = dv.object_id
where d.field_id = 11
and d.value_text = 'Infra'
;