php - Mysql sorting concated values -
i have 3 mysql tables (animal, category , animal_2_category). every animal can have 0-n categories (for example fish, pet, insect, carnivore, "can fly", etc.).
table "animal" (id, name)
1, dog 2, cat 3, bee ...
table "categories" (id, name)
1, pet 2, insect 3, mammal 4, fish 5, can fly ...
table "animal_2_category" (animal_id, category_id)
1, 1 1, 3 2, 1 2, 3 3, 2 3, 5 ...
what need now, list of category combinations. following query works:
select concat_ws("-", x.name, c.name) animal_2_category a2c1 join animal_2_category a2c2 on a2c1.animal_id = a2c2.animal_id join category c on c.id = a2c2.category_id´ join categories x group a2c2.category_id
this query wil return following:
- pet-mammal
- mammal-pet
- insect-can fly
the problem is, dublicate entries "pet-mammal" , "mammal-pet". how can modify query, 1 of them, example:
- pet-mammal
- insect-can fly
you can rewrite query as
select distinct greatest(concat_ws("-", x.name, c.name),concat_ws("-", c.name, x.name)) col animal_2_category a2c1 join animal_2_category a2c2 on a2c1.animal_id = a2c2.animal_id join categories c on c.id = a2c2.`category_id` join categories `x` on a2c1.category_id = x.id x.name <> c.name
Comments
Post a Comment