mySQL,将结果值设置为同一查询中的另一个值

时间:2016-01-20 20:28:08

标签: mysql inner-join

我有以下SQL语句:

  SELECT `entity_id`,`parent_id`,`name`
  FROM category
  WHERE is_active = 1
  ODER BY parent_id asc, position asc;

返回如下结果:

+-----------+-----------+------------+----------+
| id        | parent_id | Name       | desc     |
+-----------+-----------+------------+----------+
| 1         | NULL      | Fruit      | NULL     |
+-----------+-----------+------------+----------+
| 2         | 1         | Apple      | NULL     |
+-----------+-----------+------------+----------+

我想更新查询,以便在父ID字段中返回相应的名称。所以,我的输出将是这样的:

+-----------+-----------+------------+----------+
| id        | parent_id | Name       | desc     |
+-----------+-----------+------------+----------+
| 1         | NULL      | Fruit      | NULL     |
+-----------+-----------+------------+----------+
| 2         | Fruit     | Apple      | NULL     |
+-----------+-----------+------------+----------+

虽然我不确定这是正确的方法,但我在同一桌上使用内部联接已经玩了一段时间了。任何人都可以在这推荐一种方法。

2 个答案:

答案 0 :(得分:1)

这一定是你要找的地方:

public void executeFunction(Class class1) throws Exception{
        for(Method m : class1.getMethods()){
            if(m.getName().equals("sayHi"))
            m.invoke(class1.getConstructor().newInstance());
            //default constructor used to get a object of the class
            //if there is not default constructor this will fail
        }
    }

答案 1 :(得分:1)

Bernd Buffen答案是对的,另一种方法是在主查询中使用子查询

SELECT c.`entity_id`, IFNULL((SELECT c2.`name` FROM category c2 WHERE c.`entity_id` = c2.`parent_id`), '') as parent_name, c.`name`
FROM category c
WHERE c.is_active = 1
ORDER BY c.parent_id asc, c.position asc;