Complex subquery - is it possible?

I have 2 tables: one stores tags, the other stores. There is a mode "Get articles by tag", which basically accepts all articles with the tag "x". In my article table, I use filed, called Tagsthat stores data in such a template as "tag1, tag2, tag3, ...".

So, I want everything to work on just one request:

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 this is possible, but I would really like to use one query (with a subquery) instead of two different ones.

+3
source share
1 answer

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

, :

     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]= , [FK]=

articles_tags . ( tag_id, JOIN):

    SELECT article_id, ...
      FROM articles_tags
INNER JOIN tags ON tags.tag_id = articles_tags.tag_id
     WHERE tag_name = 'TAGNAME'
+6

Source: https://habr.com/ru/post/1765429/


All Articles