PHP / MYSQL:左连接没有得到正确的父详细信息

时间:2015-01-02 10:43:32

标签: php mysql join left-join

SELECT smirt.id as mid,
pc.packet_name as pname, 
pcs.packet_name as mainn, 
smirt.p_status as st , 
smirt.new_value as weight , 
smirt.packet_id, 
smirt.parent_packet_id 
FROM issue_receive_process AS smirt 
LEFT JOIN packet_creation AS pc ON  pc.id = smirt.packet_id
LEFT JOIN packet_creation AS pcs ON pcs.id = pc.parent_packet_id 
WHERE smirt.type = 53
AND smirt.main_kapan_id IN(1,2) 
ORDER BY smirt.packet_id

从上面的查询我得到以下细节:

From above query i am getting this which i dont want

但上面是错误

因为pname是我的子包 和mainn是我的MAIN PACKET

其实我需要(应该是)pname(NULL,0004)和mainn(0003,0002)如下(图片下面是编辑图片):

right query

as 0003,0002是主要数据包,0004是0002的子包... 0003没有任何子包......

可以帮助我,我错了。

由于

更新:PARENT TABLE IMAGE thats(issue_receive_process AS smirt)

PARENT

每位用户:KISHORE以下查询:

SELECT smirt.id
,smirt.packet_id
,smirt.main_kapan_id
,pc.id
,pc.packet_name
,pc.parent_packet_id 
FROM issue_receive_process AS smirt 
LEFT JOIN packet_creation AS pc ON  pc.id = smirt.packet_id
WHERE pc.packet_name IN ('0002','0003','0004') 
ORDER BY smirt.packet_id

以下是结果:

RESULT

第二个更新表: packet_creation下面的详细信息如下面的查询

SELECT *
FROM `packet_creation`
WHERE `id`
IN ( 5, 11, 9 )
LIMIT 0 , 30

enter image description here

1 个答案:

答案 0 :(得分:1)

我对你想要的东西感到非常困惑。

在运行测试数据时,您拥有的SQL将提供您描述为错误的数据。它正在获取记录和数据包,然后该数据包为父。如果数据包没有父节点,则返回NULL(并且应该)。

我唯一能想到的是,如果没有父记录,那么你希望将子包ID作为父包返回,并将子包返回为NULL。

如果是这样的话: -

SELECT smirt.id as mid,
        IF(pcs.packet_name IS NULL, NULL, pc.packet_name) as pname, 
        IF(pcs.packet_name IS NULL, pc.packet_name, pcs.packet_name) as mainn, 
        smirt.p_status as st , 
        smirt.new_value as weight , 
        smirt.packet_id, 
        smirt.parent_packet_id 
FROM issue_receive_process AS smirt 
LEFT JOIN packet_creation AS pc ON  pc.id = smirt.packet_id
LEFT JOIN packet_creation AS pcs ON pcs.id = pc.parent_packet_id 
WHERE smirt.type = 53
AND smirt.main_kapan_id IN(1,2) 
ORDER BY smirt.packet_id

以上每个查询结果如下:

enter image description here

HENCE最终输出我认为它来自3,4,2但应该是0003,0002,0004

enter image description here

编辑 - 将字段转换为字符以尝试强制前导零: -

SELECT smirt.id as mid,
        IF(pcs.packet_name IS NULL, NULL, CAST(pc.packet_name AS CHAR)) as pname, 
        IF(pcs.packet_name IS NULL, CAST(pc.packet_name AS CHAR), CAST(pcs.packet_name AS CHAR)) as mainn, 
        smirt.p_status as st , 
        smirt.new_value as weight , 
        smirt.packet_id, 
        smirt.parent_packet_id 
FROM issue_receive_process AS smirt 
LEFT JOIN packet_creation AS pc ON  pc.id = smirt.packet_id
LEFT JOIN packet_creation AS pcs ON pcs.id = pc.parent_packet_id 
WHERE smirt.type = 53
AND smirt.main_kapan_id IN(1,2) 
ORDER BY smirt.packet_id