webForumDet fria alternativet

Problem with COUNT, SUM and LEFT JOIN

4 svar · 298 visningar · startad av niels

nielsMedlem sedan juli 2000215 inlägg
#1

I have three tables that i want to join and fetch info from with the following query:

SELECT
domain,
SUM(revenue) AS revenue,
COUNT(DISTINCT redirections_tab.id) AS redirections,
COUNT(DISTINCT visits_tab.id) AS visits
FROM domains_tab
LEFT JOIN redirections_tab ON domains_tab.id = redirections_tab.domain_id
LEFT JOIN visits_tab ON domains_tab.id = visits_tab.domain_id
WHERE
domains_tab.client_id = '523555ae3bd12f5cc3ec406a4c8da0e9'
GROUP BY
domains_tab.id

the problem is that the SUM field 'revenue' is totally wrong since there is no DISTINCT function for SUM (and even if there was,
I would want to group by that tables id and not by 'revenue 'since these field sometimes contain the same value for multiple
records...)

How can I solve this with mysql??

thanks!
/Niels Bosma

LarsGMedlem sedan dec. 200012 465 inlägg
#2

Normally, this would be a suitable occasion to use scalar subqueries but as it is Mysql you need two queries.

Eller vill du ha ett svar på svenska?

nielsMedlem sedan juli 2000215 inlägg
#3

Så det går alltså inte att göra detta i mysql med en fråga??

LarsGMedlem sedan dec. 200012 465 inlägg
#4

Om jag gissar rätt angående din datamodell och din beskrivning så.

Du kan väl beskriva dina tabeller så...

nielsMedlem sedan juli 2000215 inlägg
#5

domains_tab är själva huvudtabellen... utifrån den vill jag sammla in data från andra tabeller där primär nyckeln i domains_tab är foreign_key.

Genererad på 373 ms · cache AV · v20260730165559-full.f96bc7eb