Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Complicated Sub-query - is this possible?

I've got 2 tables: one stores tags, the other stores articles. There's a mode "Get articles by tag", which basically takes all articles, tagged "x". In my articles table I use a filed, called Tags, that stores data in such pattern 'tag1, tag2, tag3, ...'.

So I want to get everything work by just a single query like that:

SELECT *, 
       (SELECT tagname 
          FROM `tags_table` 
         WHERE tagurn LIKE 'x') as TAGNAME 
  FROM `articles_table` 
 WHERE (Tags LIKE 'TAGNAME,%' OR Tags LIKE '%, TAGNAME' ... and so on)

I don't know if it's even possible, but I'd really like to use a single query (with a sub-query) instead of two different.

like image 303
PepeManshon Avatar asked Mar 17 '26 21:03

PepeManshon


1 Answers

This is the wrong way to store a many-to-many relationship in a database.

You should have a schema like:

     articles: [PK] article_id, ... (should have no reference to tags)
         tags: [PK] tag_id, tag_name, ...
articles_tags: [FK] article_id, [FK] tag_id

[PK] = primary key, [FK] = foreign key

Where articles_tags is a junction table. Now, you can get all articles with a given tag with (if you know the tag_id you won't even need the JOIN):

    SELECT article_id, ...
      FROM articles_tags
INNER JOIN tags ON tags.tag_id = articles_tags.tag_id
     WHERE tag_name = 'TAGNAME'
like image 196
NullUserException Avatar answered Mar 20 '26 13:03

NullUserException



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!