0

I need to display only genres which have at least two titles.

My Titles table:

Titles
------
TitleID, ArtistID, Title, StudioID, Genre

My Tracks table:

Tracks
------
TitleID, TrackNum, TrackTitle

This is my code so far:

select t.genre from titles t
join tracks tr
on (tr.titleid = t.titleid)
having count(tr.tracktitle) > 1;

I don't this the current code is answering the described question correctly.

2
  • I would have concerns about duplicate rows. Probably need to add a distinct inside the count(). Why don't you think it's correct? Commented Nov 20, 2013 at 21:13
  • Do you need the Tracks table in there at all? It sounds like you only need the Titles table for this. Commented Nov 20, 2013 at 21:14

2 Answers 2

5

If you want to use HAVING with a real meaning, you should use GROUP BY

SELECT t.genre, count(tr.tracktitle) num_tracktitle
FROM titles t
    JOIN tracks tr
       ON (tr.titleid = t.titleid)
GROUP BY t.genre
HAVING num_tracktitle > 1;
Sign up to request clarification or add additional context in comments.

2 Comments

Use having num_tracktitle > 1 so you don't have to count twice.
Sidenote: MySQL is optimised enough that it does not count twice.
0

Why do you need the tracks table? It seems like you have everything you need in the title table.

SELECT
    TI.Genre,
    Count(TI.TitleID) As Titles
FROM
    Titles TI
GROUP BY
    TI.Genre
HAVING
    COUNT(TI.TItleID) > 1

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.