dqwd71332 2016-12-28 22:27
浏览 321
已采纳

如何使用mysql查询获取parent_id?

If my SQL query is like this :

SELECT * FROM master_lookups WHERE `type` = 'fungsi'`, 

then the result is like this:

enter image description here

(image 1)

If my SQL query is like this :

SELECT @rownum := @rownum + 1 AS id,
       NULL AS parent_id,
       kdsfungsi AS `code`,
       nmsfungsi AS `name`,
       'sub_fungsi' AS `type`, 
       CONCAT('{"kdfungsi":"', kdfungsi, '"}') AS information 
FROM   dblaplakgar.t_sfungsi 
CROSS JOIN (SELECT @rownum := 735) r

then the result is like this:

enter image description here

(image 2)

I want the result of image 2, there exists the value parent_id. The value of field parent_id is taken from the id in the image 1, based on the field kdfungsi.

So as regards the value parent_id in image 2, the result is like this:

  • id 736, its parent id: 735
  • id 737, its parent id: 735
  • id 738, its parent id: 734

Once I get parent_id, I use this query to insert:

INSERT INTO master_lookups (id,parent_id,`code`,`name`,`type`,information)
SELECT @rownum := @rownum + 1 AS id,
       NULL AS parent_id,
       kdsfungsi AS `code`,
       nmsfungsi AS `name`,
       'sub_fungsi' AS `type`, 
       CONCAT('{"kdfungsi":"', kdfungsi, '"}') AS information
FROM   dblaplakgar.t_sfungsi 
CROSS JOIN (SELECT @rownum := 735) r

There are parent_id values that are still NULL.

I need to fill the parent_id on image 2 based on the field kdfungsi as seen on image 1.

How can I do that?

  • 写回答

1条回答 默认 最新

  • douqi3913 2016-12-28 22:52
    关注

    To get the id value from the master_lookups table, you could do this:

    SELECT     @rownum := @rownum + 1 AS id,
               m.id AS parent_id,
               t.kdsfungsi AS `code`,
               t.nmsfungsi AS `name`,
               'sub_fungsi' AS `type`, 
               CONCAT('{"kdfungsi":"', t.kdfungsi, '"}') AS information 
    FROM       dblaplakgar.t_sfungsi t 
    LEFT JOIN  master_lookups m
           ON  m.type = 'fungsi'
           AND m.code = t.kdfungsi
    CROSS JOIN (SELECT @rownum := 735) r
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?