Search code examples
mysqlsqlqsqlquery

Get rows which are related to the searched row, by specific column


I am trying to implement a sql query to below scenario,

user_id nic_number reg_number full_name code
B123 12345 1212 John 123
B124 12346 1213 Peter 124
B125 12347 1214 Darln 125
B123 12345 1212 John 126
B123 12345 1212 John 127

In the subscribers table there can be rows with same user_id , nic_number , reg_number , full_name. But the code is different.

First -> get the user who have same code i have typed in the query ( i have implemented a query for that and it is working fine)

Second -> Then in that data i need to find the related rows (check by nic_number, and reg_number) and display only those related rows. That means in the below query I have got the data for code = 123. Which will show the first row of the table. But I need to display only the rest of the rows which have the same nic_number or reg_number for the searched code only once. That means the last 2 rows of the table.

select code,
GROUP_CONCAT(distinct trim(nic_number)) as nic_number,
GROUP_CONCAT(distinct trim(reg_number)) as reg_number,
GROUP_CONCAT(distinct trim(full_name)) as full_name from subscribers
where code like lower(concat('123')) group by code;

I need to implement sql query for this scenario by changing the above query.(Only one query, without joins or triggers). I have tried this for a long time and unable to get the result. If anyone of you help me to get the result it will be very helpful.


Solution

  • You can combine nic and reg numbers in a unique key to get your records.

    EDITED to extract only related rows and not the one searched by code, by the way, code seems not to be unique in subscribers table.

    select 
        code,
        trim(nic_number) as nic_number,
        trim(reg_number) as reg_number,
        trim(full_name) as full_name,
        trim(code) as code 
    from 
        subscribers s1
    where 
        code <> lower(trim('123')) 
        and trim(nic_number) + '|' + trim(reg_number) IN (
            select trim(nic_number) + '|' + trim(reg_number)
            from subscribers
            where code = lower(trim('123'))
        )