简体   繁体   中英

mysql from a result, how to select rows that have same values in 2 column

In my MySQL database, the below query

SELECT c.cas_number, c.description c_desc, 
        sm.description sm_desc, sm.id sm_id, sm.component_id,
        c.id 
FROM starting_material sm 
    join component c ON c.id=sm.component_id;

returns a portion of data as below

在此处输入图像描述

And from this result, I am trying to select all rows which have the same value for the two columns c_decs and sm_desc

I tried this query but it returns only 2 rows, but I can physically see there are many rows matching

select r.cas_number, r.c_desc, r.sm_desc 
from (
        SELECT c.cas_number, c.description c_desc, 
                sm.description sm_desc, sm.id sm_id, sm.component_id,
                c.id 
        FROM starting_material sm 
            join component c ON c.id=sm.component_id
     ) as r
where r.c_desc like r.sm_desc;

I also tried this but still only 2 records in the result.

SELECT c.cas_number, c.description, sm.description 
FROM starting_material sm 
    join component c ON c.id=sm.component_id
where trim(c.description) = trim(sm.description);

Update:-

Only matching results are

在此处输入图像描述

try something like this

SELECT c.cas_number, c.description, sm.description
FROM starting_material sm 
join component c ON c.id = sm.component_id
where c.description = sm.description

Thanks, guys I did the below steps to find out the issue

By using string compare (STRCMP) I found out which records are not matching. Mostly all records did not match (with value 1) other than 2 records (value 0)

SELECT c.cas_number, c.description, sm.description, STRCMP(c.description, sm.description) FROM starting_material sm join component c ON c.id=sm.component_id;

在此处输入图像描述

It turns out one of the columns sm.description have a carriage return at the end \r

The below query helped to get all matching records.

SELECT c.cas_number, c.description, sm.description FROM starting_material sm join component c ON c.id=sm.component_id
where sm.description like concat(c.description, '\r');

I fixed the carriage return with below query

update starting_material set description=REPLACE(description,'\r','');

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