Search code examples
mysqlsqldatabaseselectsql-like

Using a value from a column as a value in an expression in LIKE statement


I have a table users with registered users in the database of my website that has columns like username and real_name, emails, passwords, etc. I want to get all entries that contain their username in their real name.

Example:

id | username   | real_name
------------------------------
1  | JoshGrimes | JoshGrimesOG
2  | DanLurk    | Daniel Lurk
3  | AdamLevine | AdamLevineGJ

I need to select entries 1 and 3 as they contain their real name contains an exact match of their username.


Solution

  • You can use like:

    select t.*
    from t
    where real_name like concat('%', username, '%');
    

    You can also use locate() or position():

    where locate(username, realname) > 0;