Last active
August 29, 2015 14:23
-
-
Save maier-stefan/4c15cf302ea4e4c84a84 to your computer and use it in GitHub Desktop.
Joins Query
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Campaign | |
has_many :campaign_offers | |
CampaignOffer | |
has_many :campaign_offer_reports | |
belongs_to :campaign | |
CampaignOfferReport | |
belongs_to :campaign_offer | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Campaign.joins(:campaign_offers, :campaign_offer_reports).select("campaigns.*","sum(campaign_offer_reports.profit) as cor_profit").group("campaigns.id") | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SELECT campaigns.*, sum(campaign_offer_reports.profit) as cor_profit FROM `campaigns` INNER JOIN `campaign_offers` ON `campaign_offers`.`campaign_id` = `campaigns`.`id` INNER JOIN `campaign_offers` `campaign_offers_campaigns_join` ON `campaign_offers_campaigns_join`.`campaign_id` = `campaigns`.`id` INNER JOIN `campaign_offer_reports` ON `campaign_offer_reports`.`campaign_offer_id` = `campaign_offers_campaigns_join`.`id` GROUP BY campaigns.id |
Use left join instead of inner join.
select().from("campaigns left join campaign_offers on campaigns.id = campaign_offer.campaign_id left join campaign_reports on campaigns.id = campaign_reports.campaign_id")
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
so what I get with this query is a table with campaign details and the profit of all reports of that campaign.
But I also want to display the campaigns without campaign_offers/campaign_offer_reports so profit should be then displayed as null