0

我有两个查询 1) 树和 2) 单元

第一次查询

SELECT * FROM tree WHERE entity_id = 8656 

返回以下数据:

entity id | parent_id | length
-------------------------------
8656      | 8656      | 0
8656      | 8655      | 1
8656      | 8654      | 2
8656      | 8653      | 3
8656      | 4331      | 4
8656      | 2         | 5
8656      | 1         | 6

第二次查询

SELECT * FROM units WHERE activity_id =10066

返回

id  | activity_id | activity_name | region_id | region_name 
-----------------------------------------------------------
136 | 10066       | Cricket       | 4331      | Yote
137 | 10066       | Cricket       | 8653      | Handbreath
140 | 10066       | Cricket       | 8656      | Kevb

预期结果

    entity id | parent_id | length | region_name
    --------------------------------------------
    8656      | 8656      | 0      | Kevb
    8656      | 8655      | 1      | null
    8656      | 8654      | 2      | null
    8656      | 8653      | 3      | Handbreath
    8656      | 4331      | 4      | Yote
    8656      | 2         | 5      | null
    8656      | 1         | 6      | null

我试过这个查询

SELECT tree . * , units.region_name
FROM tree
LEFT JOIN units ON tree.parent_id = units.region_id
WHERE tree.entity_id = 8656
AND units.activity_id = 10066
4

3 回答 3

2

通过移动u.activity_id =10066到 theLEFT JOIN而不是WHERE子句,我能够产生结果:

select t.entity_id,
  t.parent_id,
  t.length,
  u.region_name
from tree t
left join units u
  on t.parent_id = u.region_id
  and u.activity_id =10066
WHERE t.entity_id = 8656 

请参阅带有演示的 SQL Fiddle

于 2012-11-29T11:49:19.740 回答
0

尝试这个:

SELECT t.entity_id, t.arent_id, t.length, A.region_name
FROM tree t 
LEFT JOIN (SELECT region_id, region_name FROM units WHERE activity_id =10066 ) AS A ON t.arent_id = A.region_id 
WHERE entity_id = 8656 

或者

SELECT t. * , u.region_name
FROM tree t
LEFT JOIN units u ON t.parent_id = u.region_id AND u.activity_id = 10066
WHERE t.entity_id = 8656
于 2012-11-29T11:49:12.430 回答
0

如果你显示你的左连接查询将会很有帮助..无论如何试试这个......

    SELECT t.entity_id, t.parent_id, t.length, u.region_name from tree t
    left join units u on t.parent_id = u.region_id and u.activity_id =10066
    WHERE t.entity_id = 8656 
于 2012-11-29T11:55:56.997 回答