I want to make a query that contains the Artist Name and the respective cover video, which is the highest ID on the Link Column. In this example, the second row with ..embd/125/... The link format never changes. I am using PHP ,MySQL and innodb engine
I started by doing an INNER JOIN on these two tables:
Id | Artist
1 John Doe
2 Jane Doe
And this one
Id | Id_Artist | Link
53 1 http://example.com/embd/123/video/...
54 1 http://example.com/embd/125/video/...
55 1 http://example.com/embd/124/video/...
56 1 http://example.com/embd/122/video/...
57 2 http://example.com/embd/128/video/...
58 2 http://example.com/embd/129/video/...
59 2 http://example.com/embd/130/video/...
Which outputs the expected result with all the artists and they're videos
SELECT fp.id, fp.name, gl.link AS Video
FROM feed_post_artist AS fp
INNER JOIN gallery gl ON gl.id_artist = fp.id
Id | Id_Artist | Link
1 John Doe http://example.com/embd/123/video/...
1 John Doe http://example.com/embd/125/video/...
1 John Doe http://example.com/embd/124/video/...
1 John Doe http://example.com/embd/122/video/...
2 Jane Doe http://example.com/embd/128/video/...
2 Jane Doe http://example.com/embd/129/video/...
2 Jane Doe http://example.com/embd/130/video/...
Is it possible to use regex to compare each artist video and return only the highest link id as a result? ( First 4 rows 125 is highest, last 3 rows 130 is the highest ). I have tried using MAX() but it won't work, obviously.
Id | Id_Artist | Link
1 John Doe http://example.com/embd/125/video/...
2 Jane Doe http://example.com/embd/130/video/...
EDIT :
As Julian in the comments suggested, MySQL SUBSTR() solves this particular case. However, when the id goes over 999, it will stop working.
SELECT fp.id, fp.name, SUBSTR(gl.link,28,5) AS Video
FROM feed_post_artist AS fp
INNER JOIN gallery gl ON gl.id_artist = fp.id
The only part missing is grouping the results to return only the MAX()
select a.Id
,a.Artist
,g.Link
from feed_post_artist as a
left join (select Id_Artist
,substr(max(concat(lpad(substring_index(substring_index(Link,'/',5),'/',-1),10,'0'),Link)),11) as Link
from gallery as g
group by Id_Artist
) g
on g.Id_Artist =
a.Id
order by a.Id
+----+----------+---------------------------------------+
| Id | Artist | Link |
+----+----------+---------------------------------------+
| 1 | John Doe | http://example.com/embd/125/video/... |
+----+----------+---------------------------------------+
| 2 | Jane Doe | http://example.com/embd/130/video/... |
+----+----------+---------------------------------------+