S
S
SoloMidPlzD2016-06-29 10:47:32
MySQL
SoloMidPlzD, 2016-06-29 10:47:32

SQL SELECT article by tags?

There is such a scheme:
articles (id, name)
tags (id, name)
article_tags (article_id,
tag_id
) 2 query: SELECT article_id WHERE tag_id in (1,2,3,4)
and then the same with article: SELECT * WHERE id in (1,2,3,4)
This generally worked correctly.
But now I still need to filter articles that don't have a tag. I also tried stupidly to do it (I chose two arrays of article ids - exactly what I needed and didn’t need + array_differ and then I chose full articles, but it doesn’t work correctly :(. Sometimes it chooses what is not needed.
Help someone SQL guru
UPDATE: everything is fine, I'm a little stupid. Prepared statement for WHERE IN doesn't work. You need to first filter the tag_id array with something like

tag_ids = array_filter($tag_ids, 'ctype_digit');
и потом кидать сразу в SQL implode(',', $tag_ids);

and even with this, my method will work, although I already use the solution answer

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Dmitry Eremin, 2016-06-29
@SoloMidPlzD

SELECT * FROM articles WHERE id NOT IN (SELECT article_id FROM article_tags)

D
Dmitry Kovalsky, 2016-06-29
@dmitryKovalskiy

SELECT what your need FROM articles as a
LEFT JOIN article_tags as at ON a.id = at.article_id
WHERE at.tag_id is NULL

K
Konstantin Tsvetkov, 2016-06-29
@tsklab

But now I still need to filter articles that don't have a tag.

SELECT articles.ID, articles.Name
  FROM articles LEFT OUTER JOIN  article_tags ON articles.ID = article_tags.article_id
  WHERE (article_tags.tag_id IS NULL)

tag from list
We create a table of this list.
CREATE TABLE [dbo].[tag_list](
  [ID] [int] NULL,
  [tag_id] [int] NULL
) ON [PRIMARY]

And we get the desired set:
SELECT DISTINCT articles.ID, articles.Name
  FROM articles INNER JOIN article_tags ON articles.ID = article_tags.article_id 
                         INNER JOIN tag_list ON article_tags.tag_id = tag_list.tag_id

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question