简体   繁体   中英

Select within a select based on results MySQL

I have a table eg

Artist     Title      Song Key
A          Title A    A
A          Title A    B
A          Title A    F
B          Title B    A

I want to return each individual song but also show how many versions there are of that song eg Ideal results would be:

Artist     Title       How_many
A          Title A     3
B          Title B     1

This is what I'm trying but the count counts all tracks and not just from the current line:

SELECT *, 
       ( select count(*) 
           from tracks 
          where artist=artist 
            AND title=title ) as How_many 
  from tracks
 where easytosing='Yes'
 group by title, artist
 order by track_id desc

Is this possible using a nested query or is there a better way?

try this:

SELECT Artist, title, count(*) as How_many 
FROM tracks
WHERE easytosing='Yes'
GROUP BY Artist,Title
SELECT t.*, how_many
        from tracks t
inner join 
( select title,artist, count(*)  ,how_many
           from tracks 
          group by artist,title ) as temp
temp.title=t.title and temp.artist=t.artist
 where easytosing='Yes'
SELECT Artist,Title, COUNT(*) FROM TABLE1 GROUP BY Artist,Title

样本区

Just simply you can execute the following query with group by

  select Artist,Title,count(Song_Key) as How_many
  from Tracks
  group by Artist,Title

once you execute above query you will get the result as you like.

   ARTIST   TITLE   HOW_MANY
     A      Title A     3
     B      Title B     1

2 rows returned in 0.00 seconds

In the specific case:

SELECT title, artist, count(*)
from tracks
where easytosing='Yes'
group by title, artist

because you get for every artist / title the number of songs.

You don't need of subquery in this case.

Another query you can perform is a query where the main select is based on disk table (I think you have a disk table where you have a foreign key at the artist and a name of your disk) where you get a number of contained song for each artist / disk.

In this way if there are no songs for one disk you get zero value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM