I can't for the life of me get this statement to work.
SELECT max(pm.timestamp), pm.id, pm.p_media_user_id, pm.p_media_type,
pm.p_media_file, pm.wall_post, pm.p_media_location,pm.p_media_location_name,
pm.p_media_category, pa.p_source_alert_id, pa.post_id, pa.p_target_alert_id,
pu.fb_id, pu.username, pu.city, pu.sex, pu.main_image
FROM p_media as pm
INNER JOIN p_users as pu ON pm.p_media_user_id = pu.fb_id
LEFT JOIN p_alerts as pa ON pm.id = pa.post_id AND pa.p_source_alert_id ='3849084'
group by pm.p_media_user_id;
The only thing that I am having issues with is the max(pm.timestamp), after the grouping I would expect it to show the NEWEST rows in the p_media table, but to the contrary it's doing the exact opposite and showing the oldest rows. So, I need the newest rows from the p_media table grouped by the user id which Join the p_users table.
Thanks in advance, if anyone helps.
As others have already pointed out, you are aggregating by the p_media_user_id column but then selecting other non aggregate columns. This either won't run at all, or it will run but give non determistic results. However, it looks like you just want the most recent record from the p_media table, for each p_media_user_id.
If so, then this would seem to be the query you intended to run:
SELECT
pm1.timestamp, pm1.id, pm1.p_media_user_id, pm1.p_media_type, pm1.p_media_file,
pm1.wall_post, pm1.p_media_location, pm1.p_media_location_name,
pm1.p_media_category, pa.p_source_alert_id, pa.post_id, pa.p_target_alert_id,
pu.fb_id, pu.username, pu.city, pu.sex, pu.main_image
FROM p_media as pm1
INNER JOIN
(
SELECT p_media_user_id, MAX(timestamp) AS max_timestamp
FROM p_media
GROUP BY p_media_user_id
) pm2
ON pm1.p_media_user_id = pm2.p_media_user_id AND
pm1.timestamp = pm2.max_timestamp
INNER JOIN p_users AS pu
ON pm1.p_media_user_id = pu.fb_id
LEFT JOIN p_alerts AS pa
ON pm1.id = pa.post_id AND
pa.p_source_alert_id = '3849084';
Your query is not doing what you think it is doing. When you use GROUP BY, only the columns that appear in the GROUP BY clause can be used in the SELECT without an aggregate function. All columns that are not in the GROUP BY clause MUST be using in an aggregate function when adding them to the SELECT.
This is the standard, and for all databases that follow the standards, you will get an error from your query. For some reason, MySQL decided not to follow the standards on this and no error is returned. This is really bad, because your query will run, but the results cannot be predicted. So you will think that the query is fine and will wonder why you get the wrong results, while in fact your query is invalid.
MySQL has finally addressed the problem and starting with MySQL 5.7.5, the ONLY_FULL_GROUP_BY SQL mode is enabled by default. The reason they gave is rather silly: because GROUP BY processing has become more sophisticated to include detection of functional dependencies., but at least they've changed the default and starting with MySQL 5.7.5, it will behave like most other databases. For earlier versions, if you have access to change the settings, I recommend enabling ONLY_FULL_GROUP_BY so you get a clear error for such invalid queries.
In some cases, you really don't care about the value returned for the non-aggregate columns, if all the values are exactly the same. To let the query pass while ONLY_FULL_GROUP_BY is enabled, use the ANY_VALUE() function on those columns. The is a better approach as it clearly indicate your intention.
To learn how you can fix your query, you can read How do we select non-aggregate columns in a query with a GROUP BY clause. You need to self-join the p_media table with only the p_media_user_id and MAX(timestamp) selected on the grouping:
SELECT pm.timestamp, pm.id, pm.p_media_user_id, pm.p_media_type, pm.p_media_file,
pm.wall_post, pm.p_media_location, pm.p_media_location_name, pm.p_media_category,
pa.p_source_alert_id, pa.post_id, pa.p_target_alert_id,
pu.fb_id, pu.username, pu.city, pu.sex, pu.main_image
FROM p_media as pm
INNER JOIN (SELECT p_media_user_id, MAX(timestamp) AS max_time
FROM p_media
GROUP BY p_media_user_id
) pmm ON pm.p_media_user_id = pmm.p_media_user_id
AND pm.timestamp = pmm.max_time
INNER JOIN p_users AS pu ON pm.p_media_user_id = pu.fb_id
LEFT JOIN p_alerts AS pa ON pm.id = pa.post_id
AND pa.p_source_alert_id = '3849084';
You should be able to add an ORDER BY after the grouping and tell SQL what column you want to sort by [ASC or DESC].
SELECT max(pm.timestamp), pm.id, pm.p_media_user_id, pm.p_media_type,
pm.p_media_file, pm.wall_post, pm.p_media_location,pm.p_media_location_name,
pm.p_media_category, pa.p_source_alert_id, pa.post_id, pa.p_target_alert_id,
pu.fb_id, pu.username, pu.city, pu.sex, pu.main_image
FROM p_media as pm
INNER JOIN p_users as pu ON pm.p_media_user_id = pu.fb_id
LEFT JOIN p_alerts as pa ON pm.id = pa.post_id AND pa.p_source_alert_id ='3849084'
group by pm.p_media_user_id
ORDER BY pm.p_media_user_id DESC;
Related
I want to display all the values in my column even the null value.
Below is my code that displays all the columns data included null but it doesn't display the latest date.
SELECT
MEMB.LAST_M,
MEMB.MEMB_N,
PrintDate
FROM
MEMB
INNER JOIN tblPrint
ON MEMB.MEMB_N = tblPrint.MEMB_N
This code however displays the latest dates but doesn't display all the columns even the null values.
SELECT
MEMB.LAST_M,
MEMB.MEMB_N,
MAX(PrintDate)
FROM
MEMB
INNER JOIN tblPrint
ON MEMB.MEMB_N = tblPrint.MEMB_N
WHERE tblPrint.`PrintDate` IN (SELECT tblPrint.`PrintDate` FROM tblPrint) GROUP BY MEMB.`LAST_M`
You likely need to use LEFT JOIN instead of INNER JOIN. Without seeing the DB structure, I have no way to test to be sure, but I've run into the same issue before. LEFT JOIN fixed it for me.
With MySQL 8, window functions were implemented, so you can now include inline aggregates within a unit level query. Specifically you can add a new column to original query for Latest_Date:
SELECT
m.LAST_M,
m.MEMB_N,
p.PrintDate,
MAX(PrintDate) OVER(PARTITION BY m.MEMB_N) AS Latest_Date
FROM
MEMB m
INNER JOIN tblPrint p
ON m.MEMB_N = p.MEMB_N
The problem to your query is your WHERE clause you could try removing it and you will get the NULL values.
SELECT
MEMB.LAST_M,
MEMB.MEMB_N,
MAX(PrintDate)
FROM
MEMB
INNER JOIN tblPrint
ON MEMB.MEMB_N = tblPrint.MEMB_N
GROUP BY MEMB.LAST_M, MEMB.MEMB_N
I am quite new to Redshift SQL and have been trying to figure out what's wrong with my syntax.
My task is to join 2 tables: question and user via left join as I want to retain all values from table question.
At the moment it throws the following error message: [Amazon](500310) Invalid operation: This type of correlated subquery pattern is not supported yet; when I use left join. On the other hand, when I change the code to join it works just fine. I suspect this is because I have an aggregated function and logical expression within my subquery that makes my left join an inner join.
But as I mentioned above, I need to retain all values from table question.
Below is my code
select
qa.user_id as user_email,
i.timestamp as session_login_time,
qa.timestamp as question_ask_time,
qa.question_id,
qa.question
from
schema1.question as qa
left join
schema1.user as i
on
qa.user_id = i.email
and
i.timestamp =
(select
max(timestamp)
from schema1.user
where
timestamp <= qa.timestamp)
where user_email <> 'tester' and user_email not like '%tester.com'
group by qa.user_id, i.timestamp, qa.timestamp, qa.question_id, qa.question
The purpose of the subquery is to get the closest session_login_time to each of the question_ask_time. So, multiple rows of question can have the same session_login_time value.
Could anybody please help me identify what I am missing from my code above? How do I make my left join works?
Thank you so much!
I guess that should get you the same results without involving a sub query
select
qa.user_id as user_email,
max(i.timestamp) as session_login_time,
qa.timestamp as question_ask_time,
qa.question_id,
qa.question
from schema1.question as qa
left join schema1.user as i
on qa.user_id = i.email
and i.timestamp <= qa.timestamp
where qa.user_id <> 'tester' and qa.user_id not like '%tester.com'
group by qa.user_id, qa.timestamp, qa.question_id, qa.question
I have a select statement that uses inner joins on multiple tables, and I want to get COUNT() from one particular table, however my current statement is throwing an error:
Syntax error: unexpected 'COUNT' (count)
Helpful. I know. Gotta love MySQL's detailed and in-depth error messages.
Here is my select statement:
SELECT SE.SEId, SE.ParentME, SE.ParentSE, SE.Name, SE.Status, SE.Description,
UDC.UDCId, UDC.Code, UDC.Description,
TRM.COUNT(*)
FROM SubEquipment SE
INNER JOIN UserDefinedCode UDC ON UDC.ETId = SE.EquipmentType
INNER JOIN Terminal TRM ON TRM.SEId = SE.SEId
GROUP BY TRM.SEId
WHERE ParentME = #MEId;
What am I doing wrong? Is this possible?
You want to do the following:
SELECT SE.SEId, SE.ParentME, SE.ParentSE, SE.Name, SE.Status, SE.Description,
UDC.UDCId, UDC.Code, UDC.Description,
COUNT(DISTINCT TRM.SEID)
FROM SubEquipment SE
INNER JOIN UserDefinedCode UDC ON UDC.ETId = SE.EquipmentType
INNER JOIN Terminal TRM ON TRM.SEId = SE.SEId
WHERE ParentME = #MEId
GROUP BY 1,2,3,4,5,6,7,8,9
Because Count is an aggregate your single measures must be grouped. Plus the error you're seeing is because COUNT isn't a column in TRM. That's what it thinks you're asking for.
Try COUNT(DISTINCT [the TRM primary key field(s)]); it should count the distinct terminal "id" values, so even if the intermediate JOIN multiples the rows, you'll still get the number of terminals.
In addition to FirebladeDan's answer, (as he suggested) a subquery also cleaned this issue up:
SELECT DISTINCT SE.SEId, SE.ParentME, SE.ParentSE, SE.Name, SE.Status, SE.Description,
UDC.UDCId, UDC.Code, UDC.Description,
--Subquery to get the count
(SELECT COUNT(*) FROM Terminal WHERE TRM.SEId = SE.SEId) AS TerminalCount
FROM SubEquipment SE
INNER JOIN UserDefinedCode UDC ON UDC.ETId = SE.EquipmentType
LEFT JOIN Terminal TRM ON TRM.SEId = SE.SEId
WHERE ParentME = #MEId;
This got rid of the need for grouping the columns.
Subnote: I changed the INNER JOIN on the Terminal table to a LEFT JOIN, because if a SEId did not have any associated terminals, it would not return any information, which also called for a DISTINCT query.
I have the following query:
SELECT
`tests`.`id`,
`tests`.`created_at`,
`tests`.`updated_at`,
`tests`.`created_by`,
`tests`.`date_of_test`,
`tests`.`location`,
`tests`.`information`,
`tests`.`title`,
`tests`.`goals`,
`tests`.`deleted_at`,
`tests`.`status`,
`tests`.`tester`,
`tests`.`test_approach`
FROM `tests`
WHERE
`tests`.`id` IN (
SELECT `test_wobble`.`test_id`
FROM `project_wobble`
INNER JOIN `wobbles` ON `project_wobble`.`wobble_id` = `wobbles`.`id`
INNER JOIN `wobble_profiles` ON `wobble_profiles`.`wobble_id` = `wobbles`.`id`
INNER JOIN `wobble_profile_user` ON `wobble_profile_user`.`wobble_profile_id` = `wobble_profiles`.`id`
INNER JOIN `test_wobble` ON `test_wobble`.`wobble_id` = `wobbles`.`id`
WHERE `project_wobble`.`project_id` = '2' AND `wobble_profile_user`.`user_id` = '3'
GROUP BY `wobbles`.`id`
)
GROUP BY `tests`.`id`
ORDER BY tests.date_of_test DESC
If I run the IN query on its own, it returns
1 result
with the value 13.
the column is called "test_id"
When i run the whole above query, I get
2 results from the test table back...
with different ids... 13 and 14.
If I replace the IN query with the number 13... The SQL returns 1 result (The correct one).
What am i doing wrong here?
This query:
SELECT `test_wobble`.`test_id`
FROM `project_wobble`
INNER JOIN `wobbles` ON `project_wobble`.`wobble_id` = `wobbles`.`id`
INNER JOIN `wobble_profiles` ON `wobble_profiles`.`wobble_id` = `wobbles`.`id`
INNER JOIN `wobble_profile_user` ON `wobble_profile_user`.`wobble_profile_id` = `wobble_profiles`.`id`
INNER JOIN `test_wobble` ON `test_wobble`.`wobble_id` = `wobbles`.`id`
WHERE `project_wobble`.`project_id` = '2' AND `wobble_profile_user`.`user_id` = '3'
GROUP BY `wobbles`.`id`
groups by wobbles.id but returns test_wobble.test_id which is not a part of GROUP BY.
On each iteration, MySQL pushes the IN field into this query:
SELECT `test_wobble`.`test_id`
FROM `project_wobble`
INNER JOIN `wobbles` ON `project_wobble`.`wobble_id` = `wobbles`.`id`
INNER JOIN `wobble_profiles` ON `wobble_profiles`.`wobble_id` = `wobbles`.`id`
INNER JOIN `wobble_profile_user` ON `wobble_profile_user`.`wobble_profile_id` = `wobble_profiles`.`id`
INNER JOIN `test_wobble` ON `test_wobble`.`wobble_id` = `wobbles`.`id`
WHERE `project_wobble`.`project_id` = '2' AND `wobble_profile_user`.`user_id` = '3'
-- This is implicitly added by MySQL when optimizing
AND `test_wobble`.`test_id` = `tests`.`id`
GROUP BY `wobbles`.`id`
and then just checks if some value exists.
If you remove the GROUP BY from your IN query, you'll see that it contains both 13 and 14, but only one of those is returned when you run the query with GROUP BY.
You can also try running the second query, substituting 13 and 14 instead of tests.id and make sure the query returns something in both cases.
This might actually be considered a bug in MySQL. However, since the documentation does not specify which ungrouped and unaggregated expression will be returned from a grouped query, it's better to specify it explicitly, of side effects from the optimizer will kick in like the do in this case.
Could you please provide some sample of your data and outline what are you going to achieve with the query?
It is a little bit hard to tell without knowing what the data is. But, you do have an issue in the subquery. This is your subquery:
SELECT `test_wobble`.`test_id`
FROM `project_wobble` INNER JOIN
`wobbles`
ON `project_wobble`.`wobble_id` = `wobbles`.`id` INNER JOIN
`wobble_profiles`
ON `wobble_profiles`.`wobble_id` = `wobbles`.`id` INNER JOIN
`wobble_profile_user`
ON `wobble_profile_user`.`wobble_profile_id` = `wobble_profiles`.`id` INNER JOIN
`test_wobble`
ON `test_wobble`.`wobble_id` = `wobbles`.`id`
WHERE `project_wobble`.`project_id` = '2' AND `wobble_profile_user`.`user_id` = '3'
GROUP BY `wobbles`.`id`
Note the select and group by. These have different variables:
`test_wobble`.`test_id`
`wobbles`.`id`
I'm not sure which one you really want. But MySQL returns an indeterminate value when you run the query -- and a value that can change from one run to the next. You should fix the select and group by so they match.
The inner query exposes undefined behaviour. It is explained in the documentation on the page MySQL Handling of GROUP BY.
According to the SQL standard, the inner query is invalid. To be valid, all the columns that appear in the SELECT, HAVING and ORDER BY clauses must satisfy one of the following:
they appear in the GROUP BY clause;
are used (in SELECT, HAVING or ORDER BY) only as parameters of aggregate functions;
are functionally dependent on the GROUP BY columns.
For example, using your tables, you can put in the SELECT clause:
wobbles.id - because it appears in the GROUP BY clause;
COUNT(DISTINCT project_wobble.project_id) - even if project_wobble.project_id does not appear in GROUP BY, it can be used as a parameter of the aggregate function COUNT(DISTINCT);
any column of table wobbles, given that the column id is its PK - all the columns of table wobbles are functionally dependent on wobbles.id (their values are uniquely determined by the value of wobbles.id).
Before version 5.7.5, MySQL accepts queries that do not follow the above requirements but, as the documentation states:
In this case, the server is free to choose any value from each group, so unless they are the same, the values chosen are indeterminate, which is probably not what you want.
Starting with version 5.7.5, MySQL implements detection of functional dependence as an configurable feature (which is turned ON by default).
On 5.7.5 your inner query will trigger an error and that's all; your query is invalid, so it doesn't run at all.
On previous versions (also on 5.7.5 if the ONLY_FULL_GROUP_BY SQL mode is disabled), the query runs but its results are unpredictable. They can change from one execution to the next if, for example, a row is deleted then re-inserted.
Because the MySQL query optimizer re-organizes your whole query for better execution plan, when it is embedded in the larger query its execution is not the same as when it is ran standalone. This is another way you can observe its undefined behaviour.
How to fix your query
Extract the inner query, remove the GROUP BY clause, add more columns to the SELECT clause and look at what it produces:
SELECT DISTINCT `test_wobble`.`wobble_id`, `test_wobble`.`test_id`
FROM `project_wobble`
INNER JOIN `wobbles` ON `project_wobble`.`wobble_id` = `wobbles`.`id`
INNER JOIN `wobble_profiles` ON `wobble_profiles`.`wobble_id` = `wobbles`.`id`
INNER JOIN `wobble_profile_user` ON `wobble_profile_user`.`wobble_profile_id` = `wobble_profiles`.`id`
INNER JOIN `test_wobble` ON `test_wobble`.`wobble_id` = `wobbles`.`id`
WHERE `project_wobble`.`project_id` = '2' AND `wobble_profile_user`.`user_id` = '3'
If I'm not wrong, it will produce two rows having the same wobble_id and values 13 and 14 for column test_id.
If this result set is correct then you can remove test_wobble.wobble_id from SELECT, keep DISTINCT and put the query into the larger one.
There is no need for GROUP BY (because of the DISTINCT) and it should work faster without it.
I have a mysql query and it works fine when i use where clause, but when i donot use
where clause it gone and never gives the output and finally timeout.
Actually i have used Explain command to check the performance of the query and in both cases the Explain gives the same number of rows used in joining.
I have attached the image of output got with Explain command.
Below is the query.
I couldn't figure whats the problem here.
Any help is highly appreciated.
Thanks.
SELECT
MCI.CLIENT_ID AS CLIENT_ID, MCI.NAME AS CLIENT_NAME, MCI.PRIMARY_CONTACT AS CLIENT_PRIMARY_CONTACT,
MCI.ADDED_BY AS SP_ID, CONCAT(MUD_SP.FIRST_NAME, ' ', MUD_SP.LAST_NAME) AS SP_NAME,
MCI.FK_PROSPECT_ID AS PROSPECT_ID, MCI.DATE_ADDED AS ADDED_ON,
(SELECT GROUP_CONCAT(LT.TAG_TEXT SEPARATOR ', ')
FROM LK_TAG LT
INNER JOIN M_OBJECT_TAG_MAPPING MOTM
ON LT.PK_ID = MOTM.FK_TAG_ID
WHERE MOTM.FK_OBJECT_ID = MCI.FK_PROSPECT_ID
AND MOTM.OBJECT_TYPE = 1
AND MOTM.IS_ACTIVE = 1
) AS TAGS,
IFNULL(SUM(GET_DIGITS(MMR.RCP_AMOUNT)), 0) AS REVENUE_SO_FAR,
IFNULL(SUM(GET_DIGITS(MMR.RCP_RUPEES)), 0) AS REVENUE_INR,
COUNT(DISTINCT PMI_MONTHLY.PROJECT_ID) AS MONTHLY,
COUNT(DISTINCT PMI_FIXED.PROJECT_ID) AS FIXED,
COUNT(DISTINCT PMI_HOURLY.PROJECT_ID) AS HOURLY,
COUNT(DISTINCT PMI_ANNUAL.PROJECT_ID) AS ANNUAL,
COUNT(DISTINCT PMI_CURRENTLY_RUNNING.PROJECT_ID) AS CURRENTLY_RUNNING_PROJECTS,
COUNT(DISTINCT PMI_YET_TO_START.PROJECT_ID) AS YET_TO_START_PROJECTS,
COUNT(DISTINCT PMI_TECH_SALES_CLOSED.PROJECT_ID) AS TECH_SALES_CLOSED_PROJECTS
FROM
M_CLIENT_INFO MCI
INNER JOIN M_USER_DETAILS MUD_SP
ON MCI.ADDED_BY = MUD_SP.PK_ID
LEFT OUTER JOIN M_MONTH_RECEIPT MMR
ON MMR.CLIENT_ID = MCI.CLIENT_ID
LEFT OUTER JOIN M_PROJECT_INFO PMI_FIXED
ON PMI_FIXED.CLIENT_ID = MCI.CLIENT_ID AND PMI_FIXED.PROJECT_TYPE = 1
LEFT OUTER JOIN M_PROJECT_INFO PMI_MONTHLY
ON PMI_MONTHLY.CLIENT_ID = MCI.CLIENT_ID AND PMI_MONTHLY.PROJECT_TYPE = 2
LEFT OUTER JOIN M_PROJECT_INFO PMI_HOURLY
ON PMI_HOURLY.CLIENT_ID = MCI.CLIENT_ID AND PMI_HOURLY.PROJECT_TYPE = 3
LEFT OUTER JOIN M_PROJECT_INFO PMI_ANNUAL
ON PMI_ANNUAL.CLIENT_ID = MCI.CLIENT_ID AND PMI_ANNUAL.PROJECT_TYPE = 4
LEFT OUTER JOIN M_PROJECT_INFO PMI_CURRENTLY_RUNNING
ON PMI_CURRENTLY_RUNNING.CLIENT_ID = MCI.CLIENT_ID AND PMI_CURRENTLY_RUNNING.STATUS = 4
LEFT OUTER JOIN M_PROJECT_INFO PMI_YET_TO_START
ON PMI_YET_TO_START.CLIENT_ID = MCI.CLIENT_ID AND PMI_YET_TO_START.STATUS < 4
LEFT OUTER JOIN M_PROJECT_INFO PMI_TECH_SALES_CLOSED
ON PMI_TECH_SALES_CLOSED.CLIENT_ID = MCI.CLIENT_ID AND PMI_TECH_SALES_CLOSED.STATUS > 4
WHERE YEAR(MCI.DATE_ADDED) = '2012'
GROUP BY MCI.CLIENT_ID ORDER BY CLIENT_NAME ASC
Yes, as many people have said, the key is that when you have the where clause, mysql engine filters the table M_CLIENT_INFO --probably drammatically--.
A similar result as removing the where clause is to to add this where clause:
where 1 = 1
You will see that the performance is degraded also because mysql will try to get all the data.
Remove the where clause and all columns from select and add a count to see how many records you get. If it is reasonable, say up to 10k, then do the following,
put back the select columns related to M_CLIENT_INFO
do not include the nested one "TAGS"
remove all your joins
run your query without where clause and gradually include the joins
this way you'll find out when the timeout is caused.
I would try the following. First, MySQL has a keyword "STRAIGHT_JOIN" which tells the optimizer to do the query in the table order you've specified. Since all you left-joins are child-related (like a lookup table), you don't want MySQL to try and interpret one of those as a primary basis of the query.
SELECT STRAIGHT_JOIN ... rest of query.
Next, your M_PROJECT_INFO table, I dont know how many columns of data are out there, but you appear to be concentrating on just a few columns on your DISTINCT aggregates. I would make sure you have a covering index on these elements to help the query via an index on
( Client_ID, Project_Type, Status, Project_ID )
This way the engine can apply the criteria and get the distinct all out of the index instead of having to go back to the raw data pages for the query.
Third, your M_CLIENT_INFO table. Ensure that has an index on both your criteria, group by AND your Order By, and change your order by from the aliased "CLIENT_NAME" to the actual column of the SQL table so it matches the index
( Date_Added, Client_ID, Name )
I have "name" in ticks as it is also a reserved word and helps clarify the column, not the keyword.
Next, the WHERE clause. Whenever you apply a function to an indexed column name, it doesn't work the greatest, especially on date/time fields... You might want to change your where clause to
WHERE MCI.Date_Added between '2012-01-01' and '2012-12-31 23:59:59'
so the BETWEEN range is showing the entire year and the index can better be utilized.
Finally, if the above do not help, I would consider splitting your query some. The GROUP_CONCACT inline select for the TAGS might be a bit of a killer for you. You might want to have all the distinct elements first for the grouping per client, THEN get those details.... Something like
select
PQ.*,
group_concat(...) tags
from
( the entire primary part of the query ) as PQ
Left join yourGroupConcatTableBasis on key columns