【问题标题】:coverting join to subquery on mysql在mysql中将连接转换为子查询
【发布时间】:2019-10-29 12:15:52
【问题描述】:

我需要更改以下代码以使用子查询:

SELECT artist.name AS Banda, album.title AS Album, track.name AS Canción 
FROM artist
INNER JOIN album
ON artist.artistid = album.artistid
INNER JOIN track
ON album.albumid = track.albumid;

到目前为止我尝试过的是这样的:

SELECT artist.name AS Banda, album.title AS Album, track.name AS Canción
FROM artist, album,track
WHERE artist.artistid IN (SELECT album.artistid FROM album, track where album.albumid = track.albumid);

【问题讨论】:

  • JOIN 是最好的/干净的解决方案。你为什么要让它不必要地复杂化?
  • 仅供学术比较

标签: mysql sql subquery


【解决方案1】:

在 MySQL 中不使用JOIN 相当复杂:

select (select a.name from artist where a.artistid = t.artistid) as banda,
       t.albumname,
       t.Canción
from (select t.*,
             (select al.title from album al where al.albumid = t.albumid) as albumname,
             (select al.artistid from album al where al.albumid = t.albumid) as artistid
      from track t
     ) t;

您要编写的查询:

select (select a.name
        from artist a
        where a.artistid in (select al.artistid
                             from album al
                             where al.albumid = t.albumid
                            )
       ) as banda,
       (select al.title
        from album al
        where al.trackid = t.trackid
       ) as album,
       t.name as Canción
from tract t;

不幸的是,MySQL 通常不识别嵌套的相关子句引用。

【讨论】:

  • 非常感谢。我必须将 t.trackid 更改为 t.albumid 才能正常工作。
  • @DexterNaru 。 . .我很惊讶您接受了包含JOIN 的答案。这似乎与您的问题不一致。
猜你喜欢
  • 2016-03-02
  • 2021-06-23
  • 2021-08-08
  • 2012-06-08
  • 2018-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多