As someone who constantly has problems with databases, I'm trying to look for a solution that optimizes my database calls. Scenario is this, I'm trying to get all rows of items directly owned by the user, but also I want to get the rows of items where the user roles acts as a guest. My current query works, but I think it isn't the best forged solution for what I'm trying to achieve. This get me the results I want, but I fear when there are hundreds of rows this will get terribly slow
set #UsrId = 23;
(SELECT Eventos.Fecha, Eventos.InformacionDelEvento, Eventos.PosicionGpsSiNo, Eventos.InformacionGps, Dispositivos.Nombre, CatalogoDeEventos.Descripcion
FROM Eventos, CatalogoDeEventos, Dispositivos, DispositivosxUsuario
WHERE Eventos.IdEvento = CatalogoDeEventos.Id
AND Dispositivos.IdentificadorUnico = Eventos.IdDispositivo
AND DispositivosxUsuario.IdDispositivo = Dispositivos.Id
AND Dispositivos.Invisible = 0
AND DispositivosxUsuario.IdUsuario = #UsrId
ORDER BY Fecha DESC)
UNION
(SELECT Eventos.Fecha, Eventos.InformacionDelEvento, Eventos.PosicionGpsSiNo, Eventos.InformacionGps, Dispositivos.Nombre, CatalogoDeEventos.Descripcion
FROM Eventos, CatalogoDeEventos, Dispositivos, DispositivosxUsuario, Seguidores
WHERE Eventos.IdEvento = CatalogoDeEventos.Id
AND Dispositivos.IdentificadorUnico = Eventos.IdDispositivo
AND DispositivosxUsuario.IdDispositivo = Dispositivos.Id
AND Dispositivos.Invisible = 0
AND Seguidores.IdUsuario = DispositivosxUsuario.IdUsuario
AND Seguidores.IdSeguidor = #UsrId
ORDER BY Fecha DESC)
So both queries have this same block
SELECT Eventos.Fecha, Eventos.InformacionDelEvento, Eventos.PosicionGpsSiNo, Eventos.InformacionGps, Dispositivos.Nombre, CatalogoDeEventos.Descripcion
FROM Eventos, CatalogoDeEventos, Dispositivos, DispositivosxUsuario
WHERE Eventos.IdEvento = CatalogoDeEventos.Id
AND Dispositivos.IdentificadorUnico = Eventos.IdDispositivo
AND DispositivosxUsuario.IdDispositivo = Dispositivos.Id
AND Dispositivos.Invisible = 0
They differ on the lines above this, so far I haven't figured a way of getting both results on a single call
this should work
SELECT Eventos.Fecha, Eventos.InformacionDelEvento, Eventos.PosicionGpsSiNo, Eventos.InformacionGps, Dispositivos.Nombre, CatalogoDeEventos.Descripcion
FROM Eventos, CatalogoDeEventos, Dispositivos, DispositivosxUsuario, Seguidores
WHERE Eventos.IdEvento = CatalogoDeEventos.Id
AND Dispositivos.IdentificadorUnico = Eventos.IdDispositivo
AND DispositivosxUsuario.IdDispositivo = Dispositivos.Id
AND Dispositivos.Invisible = 0
AND Seguidores.IdUsuario = DispositivosxUsuario.IdUsuario
AND (
(Seguidores.IdUsuario = DispositivosxUsuario.IdUsuario
AND Seguidores.IdSeguidor = #UsrId)
OR DispositivosxUsuario.IdUsuario = #UsrId)
ORDER BY Fecha DESC
as was mentioned in the comments, this effectively left joins on Sequidores and that would probably have been more obvious if the query was written with the newer join syntax.
Re-written to use newer join syntax
SELECT e.Fecha, e.InformacionDelEvento, e.PosicionGpsSiNo, e.InformacionGps, d.Nombre, cde.Descripcion
FROM Eventos e
INNER JOIN CatalogoDeEventos cde ON e.IdEvento = cde.Id
INNER JOIN Dispositivos d ON d.IdentificadorUnico = e.IdDispositivo
INNER JOIN DispositivosxUsuario du ON du.IdDispositivo = d.Id
LEFT JOIN Seguidores s ON s.IdUsuario = du.IdUsuario
WHERE d.Invisible = 0
AND (Seguidores.IdSeguidor = #UsrId
OR DispositivosxUsuario.IdUsuario = #UsrId)
ORDER BY Fecha DESC
Related
i need to fetch the record with some condtions from two table
SELECT `tbui`.`user_id`, `tbui`.`first_name`,`tbui`.`last_name`,`tbui`.`education_level`,`tbui`.`sex`,`tbui`.`country_of_origin`,`tbui`.`city`,`tbui`.`state`,`tbui`.`country`,`tbui`.`occupation`,`tbui`.`about`,TIMESTAMPDIFF(YEAR,`tbui`.`age`,CURDATE()) as age
FROM `tb_preference_dropdown` as `tbpda`
RIGHT JOIN `tb_user_answers` as `tbua` ON `tbpda`.`question_id` = `tbua`.`question_id`
RIGHT JOIN `tb_preference_questions` as `tbpa` ON `tbpa`.`user_id` = `tbpda`.`user_id`
RIGHT JOIN `tb_user_info` as `tbui` ON `tbui`.`user_id` = `tbua`.`user_id`
WHERE `tbpda`.`user_id` = 113
AND TIMESTAMPDIFF(YEAR,`tbui`.`age`,CURDATE()) >=`tbpa`.`min_age_required` AND TIMESTAMPDIFF(YEAR,`tbui`.`age`,CURDATE()) <= `tbpa`.`max_age_required`
AND `tbui`.`country_of_origin` = `tbpa`.`country_of_origin`
AND `tbua`.`user_id` != 113
AND `tbui`.`sex` != 'Female'
HAVING SUM(IF(tbpda.question_id = 1,IF(tbpda.answer_id !=0,IF(tbua.question_id =tbpda.question_id AND `tbua`.`answer_id` = tbpda.answer_id,tbua.user_id,''),true),'')) > 0
all the things working perfectly except:
HAVING SUM(IF(tbpda.question_id = 1,IF(tbpda.answer_id !=0,IF(tbua.question_id =tbpda.question_id AND `tbua`.`answer_id` = tbpda.answer_id,tbua.user_id,''),true),'')) > 0
i am getting the records which even don't match with the above condition
You are missing GROUP BY clause, re-write the query
So here is the issue. I'm trying to write a new fillrate report because the one built in is not good enough... I'm trying to run a single select statement to return both, a count of how many times an item was ordered for a specific month, and then also a count of how many times it was invoiced/shipped in full.
This code is obviously wrong, I also currently have it restricted to only look at AUG of 2015, but that is just to simplify results during testing.
I can't figure out how to do the 2nd count... This is what I was trying (brain stuck on old for each loop logic):
select inv_mast.item_id,
inv_mast.item_desc,
"YEAR" = year(oe_line.required_date),
"MONTH" = month(oe_line.required_date),
"ORDERS" = count(1),
"HITS" = (
select count(1)
from invoice_line
where invoice_line.order_no = oe_line.order_no
and invoice_line.oe_line_number = oe_line.line_no
and invoice_line.qty_shipped = oe_line.qty_ordered
)
from oe_line,
inv_mast,
inv_loc
where inv_mast.inv_mast_uid = oe_line.inv_mast_uid
and inv_mast.delete_flag = 'N'
and inv_mast.inv_mast_uid = inv_loc.inv_mast_uid
and inv_loc.location_id = '101'
and year(oe_line.required_date) = '2015'
and month(oe_line.required_date) = '8'
group by inv_mast.item_id,
inv_mast.item_desc,
year(oe_line.required_date),
month(oe_line.required_date)
order by inv_mast.item_id
To me it would seem like you could rewrite the query to use a left join on the invoice_line table instead. Without any proper test data I can't guarantee it is correct, but I think it should be.
Besides the left join I also changed to explicit joins and moved the aliases as I don't think MySQL supports the alias = column syntax.
select inv_mast.item_id,
inv_mast.item_desc,
year(o.required_date) as "YEAR",
month(o.required_date) as "MONTH",
count(1) as "ORDERS",
count(invoice_line.order_no) as "HITS"
from oe_line o
join inv_mast on inv_mast.inv_mast_uid = o.inv_mast_uid
join inv_loc on inv_mast.inv_mast_uid = inv_loc.inv_mast_uid
left join invoice_line on invoice_line.order_no = o.order_no
and invoice_line.oe_line_number = o.line_no
and invoice_line.qty_shipped = o.qty_ordered
where inv_mast.delete_flag = 'N'
and inv_loc.location_id = '101'
and year(o.required_date) = '2015'
and month(o.required_date) = '8'
group by inv_mast.item_id,
inv_mast.item_desc,
year(o.required_date),
month(o.required_date)
order by inv_mast.item_id;
I'm facing a problem and I'm not finding the answer. I'm querying a MySql table during my java process and I would like to exclude some rows from the return of my query.
Here is the query:
SELECT
o.offer_id,
o.external_cat,
o.cat,
o.shop,
o.item_id,
oa.value
FROM
offer AS o,
offerattributes AS oa
WHERE
o.offer_id = oa.offer_id
AND (cat = 1200000 OR cat = 12050200
OR cat = 13020304
OR cat = 3041400
OR cat = 3041402)
AND (oa.attribute_id = 'status_live_unattached_pregen'
OR oa.attribute_id = 'status_live_attached_pregen'
OR oa.attribute_id = 'status_dead_offer_getter'
OR oa.attribute_id = 'most_recent_status')
AND (oa.value = 'OK'
OR oa.value='status_live_unattached_pregen'
OR oa.value='status_live_attached_pregen'
OR oa.value='status_dead_offer_getter')
The trick here is that I need the value to be 'OK' in order to continue my process but I don't need mysql to return it in its response, I only need the other values to be returned, for the moment its returning two rows by query, one with the 'OK' value and another with one of the other values.
I would like the return value to be like this:
'000005261383370', '10020578', '1200000', '562', '1000000_157795705', 'status_live_attached_pregen'
for my query, but it returns:
'000005261383370', '10020578', '1200000', '562', '1000000_157795705', 'OK'
'000005261383370', '10020578', '1200000', '562', '1000000_157795705', 'status_live_attached_pregen'
Some help would really be appreciated.
Thank you !
You can solve this with an INNER JOIN on the self I think:
SELECT o.offer_id
,o.external_cat
,o.cat
,o.shop
,o.item_id
,oa.value
FROM offer AS o
INNER JOIN offerattributes AS oa
ON o.offer_id = oa.offer_id
INNER JOIN offerattributes AS oaOK
ON oaOK.offer_id = oa.offer_id
AND oaOK.value = 'OK'
WHERE o.cat IN (1200000,12050200,13020304,3041400,3041402)
AND oa.attribute_id IN ('status_live_unattached_pregen','status_live_attached_pregen','status_dead_offer_getter','most_recent_status')
AND oa.value IN ('status_live_unattached_pregen','status_live_attached_pregen','status_dead_offer_getter');
By doing a self-JOIN with the restriction of value OK, it will limit the result set to offer_ids that have an OK response, but the WHERE clause will still retrieve the values you need. Based on your description, I think this is what you were looking for.
I also converted your implicit cross JOIN to an explicit INNER JOIN, as well as changed your ORs to IN, should be more performant this way.
I have a view with the following definition:
select
`cb_trans_detail`.`numero_partida` AS `numero_partida`,
`cb_trans_head`.`fecha_partida` AS `fecha_partida`,
`cb_trans_detail`.`concepto_partida` AS `concepto_partida`,
`cb_cuenta`.`nombre_cuenta` AS `nombre_cuenta`,
`cb_cuenta`.`codigo_mayor` AS `codigo_mayor`,
`cb_mayor`.`nombre_mayor` AS `nombre_mayor`,
`cb_mayor`.`categoria` AS `categoria`,
`cb_categoria`.`nombre` AS `nombre`,
`cb_categoria`.`presentacion` AS `presentacion`,
`cb_trans_detail`.`codigo_cuenta` AS `codigo_cuenta`,
sum(`cb_trans_detail`.`debito_partida`) AS `Debitos`,
sum(`cb_trans_detail`.`credito_partida`) AS `Creditos`,
`cb_cuenta`.`saldo_inicial` AS `saldo_inicial`,
((`cb_cuenta`.`saldo_inicial` +
sum(`cb_trans_detail`.`debito_partida`)) -
sum(`cb_trans_detail`.`credito_partida`)) AS `Saldo`,
concat(`cb_mayor`.`categoria`,`cb_cuenta`.`codigo_mayor`,`cb_trans_detail`.`codigo_cuenta`)
AS `Codigo`
from
((((`cb_trans_detail` join `cb_cuenta`
on(((`cb_trans_detail`.`codigo_cuenta` = `cb_cuenta`.`codigo_cuenta`)
and (`cb_trans_detail`.`categoria` = `cb_cuenta`.`categoria`)
and (`cb_trans_detail`.`codigo_mayor` = `cb_cuenta`.`codigo_mayor`))))
join `cb_mayor` on(((`cb_cuenta`.`codigo_mayor` = `cb_mayor`.`codigo_mayor`)
and (`cb_cuenta`.`categoria` = `cb_mayor`.`categoria`))))
join `cb_categoria` on(((`cb_mayor`.`categoria` = `cb_categoria`.`categoria`)
and (`cb_trans_detail`.`categoria` = `cb_categoria`.`categoria`))))
left join `cb_trans_head` on((`cb_trans_detail`.`numero_partida` =
`cb_trans_head`.`numero_partida`)))
where
(`cb_categoria`.`presentacion` = '1')
group by concat(`cb_mayor`.`categoria`,`cb_cuenta`.`codigo_mayor`,
`cb_trans_detail`.`codigo_cuenta`)
If I select from this view as follows:
SELECT
`balance_general_view`.`numero_partida`,
`balance_general_view`.`fecha_partida`,
`balance_general_view`.`concepto_partida`,
`balance_general_view`.`nombre_cuenta`,
`balance_general_view`.`codigo_mayor`,
`balance_general_view`.`nombre_mayor`,
`balance_general_view`.`categoria`,
`balance_general_view`.`nombre`,
`balance_general_view`.`presentacion`,
`balance_general_view`.`codigo_cuenta`,
`balance_general_view`.`Debitos`,
`balance_general_view`.`Creditos`,
`balance_general_view`.`saldo_inicial`,
`balance_general_view`.`Saldo`,
`balance_general_view`.`Codigo`
FROM
`balance_general_view`
WHERE
`balance_general_view`.`fecha_partida` BETWEEN '2014-01-01' AND '2014-01-31'
this yields a different result than if I execute the query as follows:
select
`cb_trans_detail`.`numero_partida` AS `numero_partida`,
`cb_trans_head`.`fecha_partida` AS `fecha_partida`,
`cb_trans_detail`.`concepto_partida` AS `concepto_partida`,
`cb_cuenta`.`nombre_cuenta` AS `nombre_cuenta`,
`cb_cuenta`.`codigo_mayor` AS `codigo_mayor`,
`cb_mayor`.`nombre_mayor` AS `nombre_mayor`,
`cb_mayor`.`categoria` AS `categoria`,
`cb_categoria`.`nombre` AS `nombre`,
`cb_categoria`.`presentacion` AS `presentacion`,
`cb_trans_detail`.`codigo_cuenta` AS `codigo_cuenta`,
sum(`cb_trans_detail`.`debito_partida`) AS `Debitos`,
sum(`cb_trans_detail`.`credito_partida`) AS `Creditos`,
`cb_cuenta`.`saldo_inicial` AS `saldo_inicial`,
((`cb_cuenta`.`saldo_inicial` + sum(`cb_trans_detail`.`debito_partida`)) - sum(`cb_trans_detail`.`credito_partida`)) AS `Saldo`,
concat(`cb_mayor`.`categoria`,`cb_cuenta`.`codigo_mayor`,`cb_trans_detail`.`codigo_cuenta`) AS `Codigo`
from
((((`cb_trans_detail` join `cb_cuenta` on(((`cb_trans_detail`.`codigo_cuenta` = `cb_cuenta`.`codigo_cuenta`) and (`cb_trans_detail`.`categoria` = `cb_cuenta`.`categoria`) and (`cb_trans_detail`.`codigo_mayor` = `cb_cuenta`.`codigo_mayor`)))) join `cb_mayor` on(((`cb_cuenta`.`codigo_mayor` = `cb_mayor`.`codigo_mayor`) and (`cb_cuenta`.`categoria` = `cb_mayor`.`categoria`)))) join `cb_categoria` on(((`cb_mayor`.`categoria` = `cb_categoria`.`categoria`) and (`cb_trans_detail`.`categoria` = `cb_categoria`.`categoria`)))) left join `cb_trans_head` on((`cb_trans_detail`.`numero_partida` = `cb_trans_head`.`numero_partida`)))
where
(`cb_categoria`.`presentacion` = '1') and `cb_trans_head`.`fecha_partida` BETWEEN '2014-01-01' and '2014-01-31'
group by
concat(`cb_mayor`.`categoria`,`cb_cuenta`.`codigo_mayor`,`cb_trans_detail`.`codigo_cuenta`)
My question is: How to get the result I need using the view and filtering programatically instead of hard-coding the where condition? Thank you. If you need the individual table definitions let me know. Much appreciated.
If you use a left join to a table X and a condition in the WHERE-clause to this table X, you change your left join to an inner one. If you want to restrict the results by the values of this left joined table, you must use this condition in the ON clause of the left join instead:
...
LEFT JOIN
cb_trans_head
ON
cb_trans_detail.numero_partida = cb_trans_head.numero_partida
AND
cb_trans_head.fecha_partida BETWEEN '2014-01-01' and '2014-01-31'
...
If there's another one that I overlook, tread it the same way.
i wrote a command like this to update a column in one table with avg of columns from another table.. its giving errors
UPDATE college_rating,products set
property1_avg = avg(college_rating.rating1),
property2_avg = avg(college_rating.rating2),
property3_avg = avg(college_rating.rating3),
property4_avg = avg(college_rating.rating4),
property5_avg = avg(college_rating.rating5),
property6_avg = avg(college_rating.rating6),
property7_avg = avg(college_rating.rating7),
property8_avg = avg(college_rating.rating8),
property9_avg = avg(college_rating.rating9),
property10_avg = avg(college_rating.rating10),
property11_avg = avg(college_rating.rating11),
property12_avg = avg(college_rating.rating12),
property13_avg = avg(college_rating.rating13),
property14_avg = avg(college_rating.rating14),
property15_avg = avg(college_rating.rating15)
where products.alias = concat(college_rating.property1,'-',college_rating.property2,'-',college_rating.property3)
group by college_rating.property1,college_rating.property2, college_rating.property3
The MySQL multi-table update syntax does not allow the use of group by.
You can accomplish what you are trying to do by moving the aggregation into a sub-query and joining to that sub-query in the multi-table-update instead.
Something like this should work:
update products p
inner join (
select concat(property1,'-',property2,'-',property3) as alias,
avg(rating1) as property1_avg,
avg(rating2) as property2_avg,
avg(rating3) as property3_avg,
avg(rating4) as property4_avg,
avg(rating5) as property5_avg,
avg(rating6) as property6_avg,
avg(rating7) as property7_avg,
avg(rating8) as property8_avg,
avg(rating9) as property9_avg,
avg(rating10) as property10_avg,
avg(rating11) as property11_avg,
avg(rating12) as property12_avg,
avg(rating13) as property13_avg,
avg(rating14) as property14_avg,
avg(rating15) as property15_avg
from college_rating
group by property1,property2, property3
) as r on r.alias = p.alias
set p.property1_avg = r.property1_avg,
p.property2_avg = r.property2_avg,
p.property3_avg = r.property3_avg,
p.property4_avg = r.property4_avg,
p.property5_avg = r.property5_avg,
p.property6_avg = r.property6_avg,
p.property7_avg = r.property7_avg,
p.property8_avg = r.property8_avg,
p.property9_avg = r.property9_avg,
p.property10_avg = r.property10_avg,
p.property11_avg = r.property11_avg,
p.property12_avg = r.property12_avg,
p.property13_avg = r.property13_avg,
p.property14_avg = r.property14_avg,
p.property15_avg = r.property15_avg;
What is the error that you get? And you need to have a WHERE clause unless you want the UPDATE query to apply to ALL the records
I think you'd need to use sub queries, and I'm not sure if you can update two tables like that in MySQL, at least not without prefixing the attributes.