简体   繁体   中英

MYSql left join two tables with column different values

I have two tables
1: tbl_member_registration with primary key (mem_id)
2: tbl_phone with foreign key (parent_code)

I want to left join these two tables but tbl_phone parent_code column has different values starting with prefix mem_ , how to join these two tables?

在此处输入图片说明

在此处输入图片说明

You may try the following join:

SELECT *
FROM tbl_member_registration t1
LEFT JOIN tbl_phone t2
    ON t1.mem_id = CAST(SUBSTRING_INDEX(t2.parent_code, '_', -1) AS SIGNED);

Demo

Going forward, you may want to clean up your tables such that the join condition can be had using equality = . There is no chance of an index being used on the parent_code column when it is being wrapped in an ugly call to SUBSTRING_INDEX .

I haven't checked it but you can try this will work.

select *
from tbl_member_registration tmr join tbl_phone tp
on tp.parent_code = concat('mem_',tmr.mem_id)

For more reference detail: CONCAT

I hope this will help you,its working..

SELECT *
    FROM tbl_member_registration t1
    INNER JOIN tbl_phone t2
        ON t1.mem_id = SUBSTR(t2.parent_code,5, 2);

http://rextester.com/CSBZ60078

select tbl_phone.*, tbl_member_registration.*
from tbl_member_registration.mem_id 
left join tbl_phone on tbl_member_registration.mem_id = (select substring(tbl_phone.parent_code, 5,2) );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM