B
B
Barrakuda742016-11-18 17:13:15
MySQL
Barrakuda74, 2016-11-18 17:13:15

How to select rows in sql that contain several tags at once?

Guys how to select rows in sql that contain several tags at once?
We have two tables:

FruitsTABLE
id   name
1    яблоко
2    банан
3    апельсин

FruitTagTABLE
fruit    tag
1        сладкий
1        круглый
2        сладкий
3        сладкий
3        круглый

I managed to make a request for fruits that contain any 1 tag:
SELECT DISTINCT fruitsTABLE.* FROM FruitsTABLE JOIN FruitTagTABLE ON FruitsTABLE.id = FruitTagTABLE.id WHERE FruitTagTABLE.tag = 'сладкий' OR FruitTagTABLE.tag = 'круглый'

Those. we join two tables via JOIN, find which fruits have 'sweet' or 'round' fruits and get rid of duplicates via DISTINCT.
How can I get only fruits that are both sweet AND round?
In fact, I have 3 tables, so instead of "round" "sweet" there are only tag IDs, i.e. 1 and 2. I
suppose this option, the union through GROUP_CONCAT to get the cell "1,2", and then some kind of query to look for where the fruits in such a cell contain both "1" and "2", only where is the guarantee that it won't find me fruit tagged "1.22".
In general, I think that somehow it is possible to solve this problem in a simpler way. Can you tell me which direction to dig?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Rsa97, 2016-11-18
@Barrakuda74

SELECT `f`.*
  FROM `FruitsTABLE` AS `f`
  JOIN `FruitTagTABLE` AS `ft1` ON `ft1`.`tag` = :tag1 AND `ft1`.`id` = `f`.`id`
  JOIN `FruitTagTABLE` AS `ft2` ON `ft2`.`tag` = :tag2 AND `ft1`.`id` = `f`.`id`

E
Edward, 2016-11-18
@edb

select * 
from FruitsTABLE f
where name = 'яблоко'
  and exists (select * 
              from FruitTagTABLE t 
              where t.fruit = f.fruit
                and f.tag  = 'сладкий'
             )
  and exists (select * 
              from FruitTagTABLE t 
              where t.fruit = f.fruit
                and f.tag  = 'круглый'
             )

something similar already happened:
https://toster.ru/answer?answer_id=867572

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question