Jump to content

MySQL Query - Select rows with part of a string in a column


Raider

Recommended Posts

Hey guys.

 

I don't think the title is very informative but was unable to phrase it correctly and concisely; sorry about that. Here's the longer description:

 

I wanted to make a query to a DB which only selects rows in which one of the columns contains a string (even if in that column there are other strings / words seperated by spaces). Basically, one of the columns of my table is called "tags", which, as the name indicates, contains various tags. A coouple of example rows:

 

ID (int): 1

NAME (text): "My article"

TAGS (text): "tag1, tag3"

 

 

ID (int): 2

NAME (text): "My article2"

TAGS (text): "tag2, tag4"

 

So I want to select, for example, all rows that contain "tag1" in the "tags" column, even if it isn't the only tag. Something like:

 

SELECT * FROM my_table WHERE tags = * . "tag1" . *

 

but that syntax does not work.

 

Thanks a lot in advance.

The syntax is

SELECT * FROM my_table WHERE tags LIKE '%tag1%'

-the problem with this, is it will also match tag12

-also, LIKE statements with two % tend to be slow

 

is there a reason you don't have a separate table for tags? by doing that, you have so many more options, like generating a list of all the different tags, etc

The syntax is

SELECT * FROM my_table WHERE tags LIKE '%tag1%'

-the problem with this, is it will also match tag12

-also, LIKE statements with two % tend to be slow

 

is there a reason you don't have a separate table for tags? by doing that, you have so many more options, like generating a list of all the different tags, etc

Thanks :) I haven't coded much (if at all) related to the tags part of my website, so I'll probably just make a new table for them.

Again, thanks a lot!

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.