Search code examples
mysqlsqlsql-like

How to fetch all rows from table if like operator value match using mysql?


I'm trying to fetch all record if like operator value match and is true.

I have table ticket.

---------------------------
: id  :  ticket : user_id :
---------------------------
: 1   : 2546    : 2       :
---------------------------
: 2    : 8475    : 2      :
---------------------------

I'm trying this query

SELECT * FROM `ticket` WHERE `ticket` LIKE '%2546%'  

Above query is returning single result and is working fine. But I need both rows if like operator value match and table has more record of that row user_id. I tried group by

SELECT * FROM `ticket` WHERE `ticket` LIKE '%2546%' 
GROUP BY `user_id `

I know it can be done if use user_id = 2 instead of like and Group By operator but I need to filter by ticket column. So is this possible to achieve this kind of task in single query?


Solution

  • Use a nested query:

    SELECT *
    FROM ticket t1
    WHERE user_id IN (
        SELECT DISTINCT user_id
        FROM ticket t2
        WHERE ticket LIKE '%2456%'
    );