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.

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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!

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.