Ayaz Ali Shah
Ayaz Ali Shah

Reputation: 3531

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?

Upvotes: 4

Views: 3053

Answers (2)

Saty
Saty

Reputation: 22532

Using self join as

SELECT U . * 
FROM  `ticket` t, `ticket` U
WHERE t.`ticket` LIKE  '%2546%'
AND t.`user_id` = U.`user_id` 

Upvotes: 2

hjpotter92
hjpotter92

Reputation: 80639

Use a nested query:

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

Upvotes: 6

Related Questions