如何使用mysql查询获取parent_id?

时间:2016-12-28 22:27:12

标签: php mysql mysql-5.7

如果我的SQL查询是这样的:

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

然后结果如下:

enter image description here

(图片1)

如果我的SQL查询是这样的:

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

然后结果如下:

enter image description here

(图片2)

我想要图像2的结果,存在值 parent_id 。字段 parent_id 的值取自图像1中的 id ,基于字段 kdfungsi

关于图像2中的值 parent_id ,结果如下:

  • id 736,其父ID:735
  • id 737,其父ID:735
  • id 738,其父ID:734

获得 parent_id 后,我使用此查询插入:

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

parent_id 值仍为NULL。

我需要根据图像1上的 kdfungsi 字段填写图像2上的 parent_id

我该怎么做?

1 个答案:

答案 0 :(得分:1)

要从 master_lookups 表中获取 id 值,您可以这样做:

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