Skip to content

Instantly share code, notes, and snippets.

select artists.* from artists left join (select * from songs limit 10) as s on s.artist_id = artists.id;
SELECT gigs.*
FROM gigs
JOIN (
SELECT gigs.song_id, COUNT(gigs.song_id) as theCount
FROM `gigs`
LEFT OUTER JOIN `songs` ON `songs`.`id` = `gigs`.`song_id`
HAVING theCount <= 5
) AS dt USING (song_id);
SELECT gigs.*
FROM gigs
LEFT OUTER JOIN `songs` ON `songs`.`id` = `gigs`.`song_id`
JOIN (
SELECT gigs.song_id, COUNT(gigs.song_id) as theCount
FROM `gigs`
LEFT OUTER JOIN `songs` ON `songs`.`id` = `gigs`.`song_id`
HAVING theCount <= 5
) AS dt USING (song_id);
SELECT *
FROM
channels
JOIN gigs ON channels.id = gigs.channel_id
JOIN songs ON gigs.song_id = songs.id
JOIN (
SELECT
t1.channel_id,
t1.song_id,
COUNT(t2.song_id) AS theCount
SELECT *
FROM
channels
JOIN gigs ON channels.id = gigs.channel_id
JOIN songs ON gigs.song_id = songs.id
JOIN (
SELECT t1.channel_id, t1.song_id, COUNT(t2.song_id) AS theCount
FROM gigs t1
LEFT JOIN gigs t2 ON t1.channel_id = t2.channel_id AND t1.song_id > t2.song_id
GROUP BY t1.channel_id, t1.song_id
SELECT *, channels.name as channel_name
FROM
channels
JOIN gigs ON channels.id = gigs.channel_id
JOIN songs ON gigs.song_id = songs.id
JOIN (
SELECT t1.channel_id, t1.song_id, COUNT(t2.song_id) AS theCount
FROM gigs t1
LEFT JOIN gigs t2 ON t1.channel_id = t2.channel_id AND t1.song_id > t2.song_id
GROUP BY t1.channel_id, t1.song_id
Channel.select("*").from("channels").joins(:gigs, :songs)
@channels = Channel.includes(:songs).all.map do |channel|
channel.songs.limit(10)
channel
end
#<Channel id: 14, name: "Mix Megapol Super Duper!", alias: "Mix Megapol Super Duper!", link: nil, active: true>
<%= @channels.each do |channel| %>
<h1><%= channel.alias %></h1>
<% channel.songs.each do |song| %>
<%= song.title %><br>
<% end %>
<% end %>