mySQL,将字段设置为另一个字段的值

时间:2016-01-20 15:33:18

标签: mysql subquery

我有两个单独的查询。

 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     |
    +-----------+-----------+------------+----------+

我尝试创建一个子查询来执行此操作,但我没有任何喜悦,任何人都可以建议如何构建查询。感谢

1 个答案:

答案 0 :(得分: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