So i've got this query below and it's giving me a syntax error. I will show the error below the query.
Please check below:
SELECT g.fullname, g.id as guardian_id, g.email, g.email_2, s.title, s.domain, d.device_id as device, d.os, gf.booking_open_notified, gf.days_notified_7, gf.days_notified_3, gf.day_notified, s.id as school_id, p.firstname, p.surname
FROM guardian as g
LEFT JOIN guardian_form as gf ON gf.school_id = g.school_id
LEFT JOIN school as s ON s.id = g.school_id
LEFT JOIN school_design as sd ON sd.school_id = s.id
LEFT JOIN device as d ON d.school_id = s.id AND d.guardian_id = g.id
(
LEFT JOIN pupil as p ON p.school_id = s.id AND
(
p.grade_id = gf.grade_id
OR p.grade_id = gf.grade_id_2
OR p.grade_id = gf.grade_id_3
OR p.grade_id = gf.grade_id_4
OR p.grade_id = gf.grade_id_5
OR p.grade_id = gf.grade_id_6
OR p.grade_id = gf.grade_id_7
OR p.grade_id = gf.grade_id_8
OR p.grade_id = gf.grade_id_9
OR p.grade_id = gf.grade_id_10
)
) OR (
LEFT JOIN guardian_form_group as gfg ON gfg.guardian_form_id = gf.id
LEFT JOIN pupil_group as pg ON pg.group_id = gfg.group_id
LEFT JOIN pupil as p ON p.id = pg.pupil_id AND pg.school_id = s.id
)
WHERE (
gf.booking_open_notified != 1
OR gf.days_notified_7 != 1
OR gf.days_notified_3 != 1
OR gf.day_notified != 1
)
AND gf.active = 1
AND sd.disable_parents_evening_notification_and_email = 0
GROUP BY gf.id, p.id
LIMIT 20
Error:
Error SQL query: Documentation
SELECT g.fullname, g.id as guardian_id, g.email, g.email_2, s.title,
s.domain, d.device_id as device, d.os, gf.booking_open_notified,
gf.days_notified_7, gf.days_notified_3, gf.day_notified, s.id as
school_id, p.firstname, p.surname FROM guardian as g LEFT JOIN
guardian_form as gf ON gf.school_id = g.school_id LEFT JOIN school as
s ON s.id = g.school_id LEFT JOIN school_design as sd ON sd.school_id
= s.id LEFT JOIN device as d ON d.school_id = s.id AND d.guardian_id = g.id
(
LEFT JOIN pupil as p ON p.school_id = s.id AND
(
p.grade_id = gf.grade_id
OR p.grade_id = gf.grade_id_2
OR p.grade_id = gf.grade_id_3
OR p.grade_id = gf.grade_id_4
OR p.grade_id = gf.grade_id_5
OR p.grade_id = gf.grade_id_6
OR p.grade_id = gf.grade_id_7
OR p.grade_id = gf.grade_id_8
OR p.grade_id = gf.grade_id_9
OR p.grade_id = gf.grade_id_10
)
) OR
MySQL said: Documentation
1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use
near
'JOIN pupil as p ON p.school_id = s.id AND
(
p.grade_id = gf.' at line 8
Your syntax IS LIKE
SELECT listOfColumns FROM table1 LEFT JOIN table2 (LEFT JOIN table3) OR (LEFT JOIN table4)
Why are you trying TO USE 'OR' for joining ? This is not supported. Try improving your ON conditions if you want to filter out the tables
Related
First, I searched about the same problem but I didn't find an appropriate solution.
My problem is with the following code, it's returning wrong results:
SELECT FbID,FhID,
FbRef,
FbDate,
(D.AccName) AS DName,
FbQuan,
CONCAT(CategoryName,'-',ProductName) AS ProdName,
(C.AccName) AS CusName,
FhPurPrice,FbSalePrice,
(R.AccName) AS ResoName,
Curr1.CurrencyName,
Curr2.CurrencyName,
Plc1.PlaceName AS FhResoPlaceName,
Plc2.PlaceName AS FbCusPlaceName,
'linked' AS xLinkStatus,
1 AS xStatus
FROM tblfatora2 F2
INNER JOIN tblfatora1 F1 ON F1.FhRef = F2.FhRef
INNER JOIN tblproducts P ON P.ProductID = F1.FhProduct
INNER JOIN tblcategories CT ON CT.CategoryID = P.ProductCategory
INNER JOIN tblaccounts R ON R.AccID = F1.FhReso
INNER JOIN tblaccounts C ON C.AccID = F2.FbCus
INNER JOIN tblaccounts D ON D.AccID = F1.FhDriver
INNER JOIN tblcurrencies Curr1 ON C.AccCurrID = Curr1.CurrencyID
INNER JOIN tblcurrencies Curr2 ON R.AccCurrID = Curr2.CurrencyID
LEFT JOIN tblplaces Plc1 ON F1.FhResoPlace = Plc1.PlaceID
LEFT JOIN tblplaces Plc2 ON F2.FbCusPlace = Plc2.PlaceID
WHERE FIND_IN_SET(`FhID`, '18313,18314')
ORDER BY FbDate, FbID
the results that it gives me are: enter image description here
note: I use FIND_IN_SET here because I can't use (IN) where I use that SQL statement in a procedure inside vb.net code:
Public Sub MySql_GetLinked()
xDtAll = New DataTable()
Dim xPar(0) As MySqlParameter
xPar(0) = New MySqlParameter("#FhID", MySqlDbType.String) With {
.Value = LinkedFatora}
xClsMySql.GetData(xSqlLinked, xDtAll, xPar)
End Sub
So I fill the variable (LinkedFatora) by loop and I use the same SQL statement but I replace (WHERE FIND_IN_SET('FhID', '18313,18314')) with (WHERE FIND_IN_SET('FhID', #FhID)).
I looked for the error's reason but couldn't catch it.
I found the problem, it's changing (WHERE FIND_IN_SET(FhID, '18313,18314')) to (WHERE FIND_IN_SET(FbID, '18313,18314')):
SELECT FbID,FhID,
FbRef,
FbDate,
(D.AccName) AS DName,
FbQuan,
CONCAT(CategoryName,'-',ProductName) AS ProdName,
(C.AccName) AS CusName,
FhPurPrice,FbSalePrice,
(R.AccName) AS ResoName,
Curr1.CurrencyName,
Curr2.CurrencyName,
Plc1.PlaceName AS FhResoPlaceName,
Plc2.PlaceName AS FbCusPlaceName,
'linked' AS xLinkStatus,
1 AS xStatus
FROM tblfatora2 F2
INNER JOIN tblfatora1 F1 ON F1.FhRef = F2.FhRef
INNER JOIN tblproducts P ON P.ProductID = F1.FhProduct
INNER JOIN tblcategories CT ON CT.CategoryID = P.ProductCategory
INNER JOIN tblaccounts R ON R.AccID = F1.FhReso
INNER JOIN tblaccounts C ON C.AccID = F2.FbCus
INNER JOIN tblaccounts D ON D.AccID = F1.FhDriver
INNER JOIN tblcurrencies Curr1 ON C.AccCurrID = Curr1.CurrencyID
INNER JOIN tblcurrencies Curr2 ON R.AccCurrID = Curr2.CurrencyID
LEFT JOIN tblplaces Plc1 ON F1.FhResoPlace = Plc1.PlaceID
LEFT JOIN tblplaces Plc2 ON F2.FbCusPlace = Plc2.PlaceID
WHERE FIND_IN_SET(`FbID`, '18313,18314')
ORDER BY FbDate, FbID
I'm trying to update the fields by using below query. What is the error in below query ?
MySQL said: Documentation
1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use
near 'FROM orders cl' at line 2
update hedging SET
Dept = concat(RIGHT( dpt.DeptName,2),LEFT( grp.GroupName,3),LEFT( st.Login,3)),
OrderNo = cl.OrderNo,Client = cn.ShortName,
Currency = cur.Notation, SellingAmount = pto.PIAmount ,
BuyingAmount = pto.POAmount
FROM orders cl
left join client cn on cl.ClientID = cn.ClientID
inner join department dpt on cl.DeptID = dpt.DeptID
inner join supplier sp on cl.SupplierID = sp.SupplierId
left join staff st on st.StaffID = cl.SalesPerson
left join pipo_total pto on pto.OrderNo = cl.OrderNo
inner join groups grp on cl.GroupID = grp.GroupID
left join currency cur on cur.CurrencyID= cl.SellCurrencyID
left join hedging hed on hed.OrderNo = cl.OrderNo)
where cur.Notation <> 'USD' and cl.OrderType = '1' and hed.OrderNo = cl.OrderNo
Try 1
update orders cl
left join client cn on cl.ClientID = cn.ClientID
inner join department dpt on cl.DeptID = dpt.DeptID
inner join supplier sp on cl.SupplierID = sp.SupplierId
left join staff st on st.StaffID = cl.SalesPerson
left join pipo_total pto on pto.OrderNo = cl.OrderNo
inner join groups grp on cl.GroupID = grp.GroupID
left join currency cur on cur.CurrencyID= cl.SellCurrencyID
left join hedging hed on hed.OrderNo = cl.OrderNo
SET hed.Dept = concat(RIGHT( dpt.DeptName,2),LEFT( grp.GroupName,3),LEFT( st.Login,3))
,hed.OrderNo = cl.OrderNo
,hed.Client = cn.ShortName
,hed.Currency = cur.Notation
,hed.SellingAmount = pto.PIAmount
,hed.BuyingAmount = pto.POAmount
where cur.Notation <> 'USD' and cl.OrderType = '1' and hed.OrderNo = cl.OrderNo
UPDATE with multiple tables should be something like this
UPDATE table1 t1
INNER JOIN table2 t2 ON t1.ID = t2.ID
SET t1.value = [value]
Edit: Your updated query
update orders cl
left join client cn on cl.ClientID = cn.ClientID
inner join department dpt on cl.DeptID = dpt.DeptID
inner join supplier sp on cl.SupplierID = sp.SupplierId
left join staff st on st.StaffID = cl.SalesPerson
left join pipo_total pto on pto.OrderNo = cl.OrderNo
inner join groups grp on cl.GroupID = grp.GroupID
left join currency cur on cur.CurrencyID= cl.SellCurrencyID
left join hedging hed on hed.OrderNo = cl.OrderNo)
SET Dept = concat(RIGHT( dpt.DeptName,2),LEFT( grp.GroupName,3),LEFT( st.Login,3))
,OrderNo = cl.OrderNo
,Client = cn.ShortName
,Currency = cur.Notation
,SellingAmount = pto.PIAmount
,BuyingAmount = pto.POAmount
where cur.Notation <> 'USD' and cl.OrderType = '1' and hed.OrderNo = cl.OrderNo
I have the following (simplified) query:
SELECT
u.idnumber AS user_idnumber,
sst_status.value AS scorm_status,
sst_starttime.value AS scorm_starttime,
sst_duration.value AS scorm_duration,
sst_score.value AS scorm_score,
u.id as uid,
s.id as scormid,
ss.id as ssid
FROM {user} u
LEFT JOIN {prog_user_assignment} prua ON prua.userid = u.id
LEFT JOIN {prog} pr ON prua.programid = pr.id
LEFT JOIN {prog_courseset} prcs ON prcs.programid = pr.id
LEFT JOIN {prog_courseset_course} prcsc ON prcsc.coursesetid = prcs.id
LEFT JOIN {course} c ON prcsc.courseid = c.id
LEFT JOIN {scorm} s ON s.id = cm.instance
LEFT JOIN {scorm_scoes} ss ON ss.scorm = s.id
LEFT JOIN {scorm_scoes_track} sst_status
ON sst_status.userid = u.id
AND sst_status.scormid = ss.scorm
AND sst_status.element = 'cmi_core.lesson_status'
AND sst_status.scoid = ss.id
LEFT JOIN {scorm_scoes_track} sst_starttime
ON sst_starttime.userid = u.id
AND sst_starttime.scormid = ss.scorm
AND sst_starttime.element = 'x.start.time'
AND sst_starttime.scoid = ss.id
LEFT JOIN {scorm_scoes_track} sst_duration
ON sst_duration.userid = u.id
AND sst_duration.scormid = ss.scorm
AND sst_duration.element = 'cmi.core.total_time'
AND sst_duration.scoid = ss.id
LEFT JOIN {scorm_scoes_track} sst_score
ON sst_score.userid = u.id
AND sst_score.scormid = ss.scorm
AND sst_score.element = 'cmi.core.score.raw'
AND sst_score.scoid = ss.id
WHERE u.id IN([SOME_EXAMPLE_IDS_HERE]) AND u.deleted = 0
group by u.idnumber, c.id
Now the problem is that without the GROUP BY clause, some of the records have values for scorm_status, scorm_starttime etc. However, these contain duplicates. But, with the group by statement, only NULL values are returned for these columns. Does anyone have a clue on how to resolve this?
Using GROUP_CONCAT and SUBSTRING_INDEX:-
SELECT
u.idnumber AS user_idnumber,
SUBSTRING_INDEX(GROUP_CONCAT(sst_status.value), ',', 1) AS scorm_status,
SUBSTRING_INDEX(GROUP_CONCAT(sst_starttime.value), ',', 1) AS scorm_starttime,
SUBSTRING_INDEX(GROUP_CONCAT(sst_duration.value), ',', 1) AS scorm_duration,
SUBSTRING_INDEX(GROUP_CONCAT(sst_score.value), ',', 1) AS scorm_score,
u.id as uid,
s.id as scormid,
ss.id as ssid
FROM {user} u
LEFT JOIN {prog_user_assignment} prua ON prua.userid = u.id
LEFT JOIN {prog} pr ON prua.programid = pr.id
LEFT JOIN {prog_courseset} prcs ON prcs.programid = pr.id
LEFT JOIN {prog_courseset_course} prcsc ON prcsc.coursesetid = prcs.id
LEFT JOIN {course} c ON prcsc.courseid = c.id
LEFT JOIN {scorm} s ON s.id = cm.instance
LEFT JOIN {scorm_scoes} ss ON ss.scorm = s.id
LEFT JOIN {scorm_scoes_track} sst_status
ON sst_status.userid = u.id
AND sst_status.scormid = ss.scorm
AND sst_status.element = 'cmi_core.lesson_status'
AND sst_status.scoid = ss.id
LEFT JOIN {scorm_scoes_track} sst_starttime
ON sst_starttime.userid = u.id
AND sst_starttime.scormid = ss.scorm
AND sst_starttime.element = 'x.start.time'
AND sst_starttime.scoid = ss.id
LEFT JOIN {scorm_scoes_track} sst_duration
ON sst_duration.userid = u.id
AND sst_duration.scormid = ss.scorm
AND sst_duration.element = 'cmi.core.total_time'
AND sst_duration.scoid = ss.id
LEFT JOIN {scorm_scoes_track} sst_score
ON sst_score.userid = u.id
AND sst_score.scormid = ss.scorm
AND sst_score.element = 'cmi.core.score.raw'
AND sst_score.scoid = ss.id
WHERE u.id IN([SOME_EXAMPLE_IDS_HERE]) AND u.deleted = 0
group by u.idnumber, c.id
This is getting the first non null values of these fields. Note that this is relying on the fields not containing commas (but easy enough to specify a different separator for the GROUP_CONCAT). You can specify an order for the GROUP_CONCAT to get your preferred value if required.
Here is a very simplified version of your query:
select u.idnumber AS user_idnumber, sst_status.value AS scorm_status,
sst_starttime.value AS scorm_starttime, sst_duration.value AS scorm_duration,
sst_score.value AS scorm_score, u.id as uid, s.id as scormid, ss.id as ssid
. . .
group by u.idnumber, c.id;
You will notice that most of the columns in the select are not in the group by. This is using a (mis)feature of MySQL and would not generally be allowed in other databases.
What MySQL does is it chooses an abritrary value from one of the rows for the result. The idea is that this works nicely if the column is constant for the group. But, it doesn't usually work as expected in other circumstances.
If you want a non-NULL value, then you can use max() or min() to get the biggest or smallest value.
For instance:
min(sst_status.value) AS scorm_status
and so on.
I have a query. I have created index for all joined key, pre-filter the master table and choose specific rows to select, but it still take long time to show(sometimes it hangs). What should We do to improve the performance?
SELECT *
FROM t_responden a
INNER JOIN t_kepemilikan_tik b
ON a.res_id = b.res_id
INNER JOIN t_televisi c
ON a.res_id = c.res_id
INNER JOIN t_telepon_hp d
ON a.res_id = d.res_id
INNER JOIN t_radio e
ON a.res_id = e.res_id
INNER JOIN t_media_cetak f
ON a.res_id = f.res_id
INNER JOIN t_internet g
ON a.res_id = g.res_id
LEFT JOIN t_mst_pendidikan n
ON a.res_pendidikan_kk = n.kd_pendidikan
LEFT JOIN t_mst_pendidikan o
ON a.res_pendidikan = o.kd_pendidikan
LEFT JOIN t_mst_penghasilan p
ON a.res_penghasilan = p.kd_penghasilan
LEFT JOIN t_mst_aksesibilitas q
ON a.res_aksesibilitas = q.kd_akses
LEFT JOIN t_mst_mobilitas r
ON a.res_mobilitas = r.kd_mobilitas
LEFT JOIN t_mst_pekerjaan s
ON a.res_pekerjaan = s.kode
LEFT JOIN t_mst_pengeluaran t
ON a.res_pengeluaran = t.kode
INNER JOIN t_pernyataan h
ON a.res_id = h.res_id
INNER JOIN (SELECT * FROM t_mst_prop WHERE kode IN ( '3200', '1600', '1800', '3600' )) i
ON a.res_propinsi = i.kode
INNER JOIN (SELECT * FROM t_mst_kabkota WHERE kode_prop IN ( '3200', '1600', '1800', '3600' )) j
ON ( a.res_kabkota = j.kode
AND a.res_propinsi = j.kode_prop )
INNER JOIN (SELECT * FROM t_mst_kec WHERE kode_prop IN ( '3200', '1600', '1800', '3600' )) k
ON ( a.res_kecamatan = k.kode
AND a.res_kabkota = k.kode_kabkota
AND a.res_propinsi = k.kode_prop )
INNER JOIN (SELECT * FROM t_mst_desa WHERE kode_prop IN ( '3200', '1600', '1800', '3600' ))l
ON ( a.res_keldesa = l.kode
AND a.res_kabkota = l.kode_kabkota
AND a.res_propinsi = l.kode_prop
AND l.kode_kec = a.res_kecamatan )
WHERE a.res_tahunsurvei = 2013
AND res_propinsi IN ( '3200', '1600', '1800', '3600' )
ORDER BY 1
SELECT STRAIGHT_JOIN
*
FROM
t_responden a
INNER JOIN t_kepemilikan_tik b
ON a.res_id = b.res_id
INNER JOIN t_televisi c
ON a.res_id = c.res_id
INNER JOIN t_telepon_hp d
ON a.res_id = d.res_id
INNER JOIN t_radio e
ON a.res_id = e.res_id
INNER JOIN t_media_cetak f
ON a.res_id = f.res_id
INNER JOIN t_internet g
ON a.res_id = g.res_id
LEFT JOIN t_mst_pendidikan n
ON a.res_pendidikan_kk = n.kd_pendidikan
LEFT JOIN t_mst_pendidikan o
ON a.res_pendidikan = o.kd_pendidikan
LEFT JOIN t_mst_penghasilan p
ON a.res_penghasilan = p.kd_penghasilan
LEFT JOIN t_mst_aksesibilitas q
ON a.res_aksesibilitas = q.kd_akses
LEFT JOIN t_mst_mobilitas r
ON a.res_mobilitas = r.kd_mobilitas
LEFT JOIN t_mst_pekerjaan s
ON a.res_pekerjaan = s.kode
LEFT JOIN t_mst_pengeluaran t
ON a.res_pengeluaran = t.kode
INNER JOIN t_pernyataan h
ON a.res_id = h.res_id
INNER JOIN t_mst_prop i
ON a.res_propinsi = i.kode
INNER JOIN t_mst_kabkota j
ON a.res_propinsi = j.kode_prop
AND a.res_kabkota = j.kode
INNER JOIN t_mst_kec k
ON a.res_propinsi = k.kode_prop
AND a.res_kecamatan = k.kode
AND a.res_kabkota = k.kode_kabkota
INNER JOIN t_mst_desa l
ON a.res_propinsi = l.kode_prop
AND a.res_keldesa = l.kode
AND a.res_kabkota = l.kode_kabkota
AND a.res_kecamatan = l.kode_kec
WHERE
a.res_tahunsurvei = 2013
AND a.res_propinsi IN ( '3200', '1600', '1800', '3600' )
ORDER BY
1
You should have an index on your t_responden table ON ( res_tahunsurvei, res_propinsi) to match your where qualification criteria. Additionally, all your inner joins to the other tables where you are applying the IN via sub-selects is killing you. You are already limiting on the "kode"s in the where, so if you apply that as your join you should be good.
Additionally, since all the other tables appear to be more "lookup", I've added "STRAIGHT_JOIN" to tell MySQL to query in the order the tables you have listed
I have this query.
SELECT notes.id,enter.name as 'enter_name',step.title as 'flow status',notes.user_name as user_created,notes.created,notes.rel_client_id,td_doc_nr.value_string as 'document number',enter.enter_code,
IF(!ISNULL(td_doc_nr.value_string),
(SELECT GROUP_CONCAT(product_name SEPARATOR ',') from notes d
join note_bundles b on b.note_id = d.id
join note_products p on p.doc_bundle_id = b.id
join note_product_get_fields f on f.doc_product_id = p.id
join note_product_get_field_data fd on fd.get_field_id = f.id
where d.doc_nr = td_doc_nr.value_string
and value_string ='auto')
,NULL) as test
FROM notes notes
JOIN notes_steps step ON step.id = notes.step_id
JOIN notes_enters enter ON enter.id = notes.enter_id
LEFT JOIN notes_custom_fields tf_doc_nr ON tf_doc_nr.name = 'note_number' AND tf_doc_nr.rel_entity_id = enter.id
LEFT JOIN notes_custom_field_data td_doc_nr ON td_doc_nr.rel_entity_id = notes.id AND
td_doc_nr.field_instance_id = tf_doc_nr.id
WHERE notes.enter_id in (777) AND notes.status = 1
I added this subquery to the 'if statement'
SELECT GROUP_CONCAT(product_name SEPARATOR ',') from nontes d
join note_bundles b on b.note_id = d.id
join note_products p on p.doc_bundle_id = b.id
join note_product_get_fields f on f.doc_product_id = p.id
join note_product_get_field_data fd on fd.get_field_id = f.id
where d.doc_nr = 'G7777777'
and value_string ='auto'
After this I added a new column.
SELECT GROUP_CONCAT(product_name SEPARATOR ','),GROUP_CONCAT(DISTINCT b.msisdn SEPARATOR ',') from notes d
join note_bundles b on b.note_id = d.id
join note_products p on p.doc_bundle_id = b.id
join note_product_get_fields f on f.doc_product_id = p.id
join note_product_get_field_data fd on fd.get_field_id = f.id
where d.doc_nr = 'G7777777'
and value_string ='auto'
It returns two columns.
How can I return two columns?Is it possible? :) Thanks
A subquery inside an IF statement can't return multiple columns. You will need to join the subquery into the results, and pull out the two separate columns individually:
SELECT ...
IF(!ISNULL(td_doc_nr.value_string), sub.one, NULL) as one,
IF(!ISNULL(td_doc_nr.value_string), sub.two, NULL) as two
FROM ...
LEFT JOIN (
SELECT d.doc_nr, GROUP_CONCAT(product_name SEPARATOR ','),GROUP_CONCAT(DISTINCT b.msisdn SEPARATOR ',') from documents d
join document_bundles b on b.document_id = d.id
join document_products p on p.doc_bundle_id = b.id
join document_product_cstm_fields f on f.doc_product_id = p.id
join document_product_cstm_field_data fd on fd.cstm_field_id = f.id
where value_string ='auto'
group by d.doc_nr
) sub on sub.doc_nr = td_doc_nr.value_string
A correlated subquery inside an IF statement can only return 1 column and 1 row, this is why you are getting the error. However, looking over your query the only outer reference inside the subquery is
d.doc_nr = td_doc_nr.value_string
So you do not need actually need a correlated subquery and you can achieve the same result by moving the subquery to a join and grouping by doc_nr within the subquery, which will probably be much more efficient, and it will allow you to return the 2 columns you want:
SELECT tickets.id,
source.name as 'source_name',
flow_stage.title as 'flow status',
tickets.user_name as user_created,
tickets.created,
tickets.rel_client_id,
td_doc_nr.value_string as 'document number',
source.source_code,
IF(!ISNULL(td_doc_nr.value_string), ProductNames, NULL) as test,
d.MSISDNS
FROM tickets tickets
JOIN tickets_flow_stages flow_stage
ON flow_stage.id = tickets.flow_stage_id
JOIN tickets_sources source
ON source.id = tickets.source_id
LEFT JOIN tickets_custom_fields tf_doc_nr
ON tf_doc_nr.name = 'document_number'
AND tf_doc_nr.rel_entity_id = source.id
LEFT JOIN tickets_custom_field_data td_doc_nr
ON td_doc_nr.rel_entity_id = tickets.id
AND td_doc_nr.field_instance_id = tf_doc_nr.id
LEFT JOIN
( SELECT d.Doc_nr,
GROUP_CONCAT(product_name SEPARATOR ',') AS ProductNames,
GROUP_CONCAT(DISTINCT b.msisdn SEPARATOR ',') AS MSISDNS
from documents d
INNER JOIN document_bundles b
ON b.document_id = d.id
INNER JOIN document_products p
ON p.doc_bundle_id = b.id
INNER JOIN document_product_cstm_fields f
ON f.doc_product_id = p.id
INNER JOIN document_product_cstm_field_data fd
ON fd.cstm_field_id = f.id
WHERE value_string ='auto'
GROUP BY d.Doc_nr
) d
ON d.doc_nr = td_doc_nr.value_string
WHERE tickets.source_id IN (114,122,125,129,131)
AND tickets.status = 1