3

In the table tags I have the field id. In the table tastings I have a field tags which is a list of id numbers separated by commas, for example 2,4,5. The database is MySQL.

Now I am trying to count how many times each tag is used in total. But I am stuck with the LIKE part. I have tried the following, all giving a syntax error:

SELECT tags.id, tag, FROM tags, tastings WHERE tags LIKE tags.id + '%'

SELECT tags.id, tag, FROM tags, tastings WHERE tags LIKE tags.id & '%'

SELECT tags.id, tag, FROM tags, tastings WHERE tags LIKE CONCAT(tags.id, '%')

What am I doing wrong?

5
  • Which DBMS? It might matter. Commented Jan 11, 2012 at 8:22
  • Did you try this ? SELECT tags.id, tag, FROM tags, tastings WHERE tags LIKE '%' + tags.id + '%' Commented Jan 11, 2012 at 8:23
  • I use MySQL. And yes I have tried those. Commented Jan 11, 2012 at 8:25
  • SQL concatenation operator is ||. Commented Jan 11, 2012 at 8:36
  • If I try the || I get weird results, it seems to be not the same as using CONCAT() Commented Jan 11, 2012 at 8:45

3 Answers 3

9

I helps if you post the error, but you have an extra comma after the select list. Also, you might need to qualify tags, since it is both a table and a column.

Try this:

SELECT tags.id, tag
FROM tags, tastings
WHERE tastings.tags LIKE CONCAT('%', tags.id, '%')

or better, use the new join syntax:

SELECT tags.id, tag
FROM tags
JOIN tastings on tastings.tags LIKE CONCAT('%', tags.id, '%')

Note the sandwiching of tag.id in % so you find the id anywhere in it.

Warning: This join will hit id 4 when tags are 13,14,15 (there's a 4 in 14), so unless your ids are all less than 10, you'll need to rethink your join criteria.

Sign up to request clarification or add additional context in comments.

Comments

1

You haven't specified your DBMS so I'm taking a guess at what is supported.

How about

SELECT tags.id, tastings.tag
FROM tags 
    INNER JOIN tastings  
        ON tastings.tags like '%' + tags.id + '%'

This should work (again, depending on your DBMS) but you should really normalize your data, this type of thing really isn't going to scale/perform well.

Comments

1

Try the below query.

select t.id , count(t.id) from tag t , tastings tas where tas.tags like '%' ||t.id||'%'
group by t.id;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.