简体   繁体   中英

Mysql Select Like query

I am a beginner in SQL. I wanted to show all the rows that has 'P1' but my query not giving me my desired output I have table named 'tbl1' like this

tbl1

id          Name           Tag
8756        ADD            P2;P3;P10;P11;P12;P15
7861        Add1           P6;P4;P5;P2;P3;P1
7823        Place          P11;P12;P10;P8;P9;P6;P7;P4;P5;P2;P3
5567        Tun            P12;P10;P8;P9;P1;P6;
6789        lac            P3;

My query is like this

SELECT id,name,tag FROM tbl1 WHERE tag LIKE '%P1%'

but my output is like this

id          Name           Tag
8756        ADD            P2;P3;P10;P11;P12;P15
7861        Add1           P6;P4;P5;P2;P3;P1
7823        Place          P11;P12;P10;P8;P9;P6;P7;P4;P5;P2;P3
5567        Tun            P12;P10;P8;P9;P1;P6;

my desired output is only those who has p1 which should only be this two only. is it possible?

 id          Name           Tag
 7861        Add1           P6;P4;P5;P2;P3;P1
 5567        Tun            P12;P10;P8;P9;P1;P6;
  • Firstly, it is not a good practice to store multiple values as delimiter-separated string in a RDBMS. You should consider normalizing your data.
  • However, in this case, you can utilize Find_in_set() function, to look for a substring inside a comma-separated string.
  • But, you have a semicolon-separated string instead. So, we can use Replace() function to replace all the commas with semicolon, and use Find_in_set() afterwards.

Try the following instead:

SELECT id,name,tag 
FROM tbl1 
WHERE FIND_IN_SET(REPLACE(tag, ';', ','), 'P1') > 0

Because you are looking for anything that contains P1, you are getting all other records as P10 contains P1. As your values are separated by ; , you can check for anything that is like %P1;% or if P1 is the last value, %P1

SELECT id,name,tag FROM tbl1 WHERE tag LIKE '%P1;%' or tag like '%P1'

The problem with your table is presented with the occurrences P11 and P1 when executing the sample code that you raise.

LIKE '% P1%' is consistent for both labels.

I would use a regular expression in the SQL statement.

For the case that you are wanting to solve would be:

WHERE column1 regexp 'P1$';
  • P1 matches the characters P1 literally (case sensitive)
  • $ asserts position at the end of a line

您可以使用OR运算符查询P1行:

SELECT id,name,tag FROM tbl1 WHERE (tag LIKE '%P1;%' or tag LIKE '%P1');

Your like is matching P11 and P12 etc as well as P1

You can do the following things, first look for ;P1; rather than P1

Second, fix the edge cases (where the tag is first of last). something like:

SELECT id,name,tag FROM tbl1 WHERE concat(';',tag,';') LIKE '%;P1;%'

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