2016-01-20 198 views
0

當我有兩個單獨的查詢時。mySQL,將字段設置爲另一個字段的值

Select `entity_id`,`parent_id`,`name`,`meta_description` 
    from catalog_category_flat_store_1 
    where level = 3 
    and is_active = 1 
    order by parent_id asc, position asc 

,給了我這樣的輸出:

+-----------+-----------+------------+----------+ 
| entity_id | parent_id | Name  | desc  | 
+-----------+-----------+------------+----------+ 
|  1 |  0 |  test | text  | 
+-----------+-----------+------------+----------+ 

我有這樣一個單獨的查詢,

Select `entity_id`,`parent_id`,`name`,`meta_description` 
     from catalog_category_flat_store_1 
     where level = 2 
     and is_active = 1 
     order by parent_id asc, position asc 

,給了我這樣的輸出:

+-----------+-----------+------------+----------+ 
    | entity_id | parent_id | Name  | desc  | 
    +-----------+-----------+------------+----------+ 
    |  2 |  1 |  test2 | text  | 
    +-----------+-----------+------------+----------+ 

我需要結合他們Ë兩個查詢,從而使輸出看起來像這樣:

+-----------+-----------+------------+----------+ 
    | entity_id | parent_nm | Name  | desc  | 
    +-----------+-----------+------------+----------+ 
    |  2 |  test |  test2 | text  | 
    +-----------+-----------+------------+----------+ 

我試圖創建一個子查詢做到這一點,但我有沒有快樂,任何人都可以提出查詢可能如何構建。謝謝

回答

0

這是做你想做的? 不是子查詢,而是將表加入自己 - 您需要使用別名來區分表的兩個實例。您可能需要修改「order by」以獲得您所需的訂購 - 因爲您的示例只有1個結果,我猜測。

Select a.`entity_id`,b.`Name` as `parent_nm`,a.`name`,a.`meta_description` 
from catalog_category_flat_store_1 a 
join catalog_category_flat_store_1 b on a.`parent_id`=b.`entity_id` and b.`level`=3 and b.`is_active`=1 
where a.level = 2 
and a.is_active = 1 
order by a.parent_id asc, b.parent_id asc, a.position asc, b.position asc 
相關問題