简体   繁体   English

在基于结果的选择中选择MySQL

[英]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: 这是我正在尝试的方法,但count不仅包括当前行,还包括所有轨道:

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 只需简单地使用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 2行在0.00秒内返回

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. 这样,如果一个磁盘上没有歌曲,您将得到零值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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