Related
I need to translate this query which works in SQL Server to MySQL. I've circled around it at least 50 times and am stumped and cannot even find a starting point.
The issues in a nutshell:
It has not one but two FULL OUTER joins which MySQL does not do. I
know this can be emulated some how using UNION in combination with LEFT and RIGHT joins.
It joins the tables on multiple conditions and I am not sure how to add exclusion
criteria in the ON if doing a typical RIGHT JOIN
SELECT COALESCE(ca.reporting_period, s_p.reporting_period, s_uy.reporting_period) AS reporting_period,
COALESCE(ca.state, s_p.state, s_uy.state) AS state,
COALESCE(ca.servicer, s_p.servicer, s_uy.servicer) AS servicer,
COALESCE(ca.product, s_p.product, s_uy.product) AS product,
COALESCE(ca.product_group, s_p.product_group, s_uy.product_group) AS product_group,
COALESCE(ca.portfolio, s_p.portfolio, s_uy.portfolio) AS portfolio,
COALESCE(ca.channel, s_p.channel, s_uy.channel) AS channel,
ca.Gross,
ca.Costs,
ca.commission,
ca.commissionable,
s_p.WAVG_placed_numerator,
s_p.place_balance AS WAVG_placed_denominator,
SUM(s_uy.cum_gross) AS gross_uy_num,
SUM(s_uy.cum_netnet) AS netnet_uy_num,
SUM(s_uy.cum_commission) AS servicer_uy_num,
SUM(s_uy.num_accounts) AS uy_den,
ca.costs_recovered
# INTO adhoc_work.RevenueReport_Legal
FROM adhoc_work.Cash ca
FULL OUTER JOIN adhoc_work.Summary_placed s_p
ON ca.reporting_period = s_p.reporting_period
AND ca.state = s_p.state
AND ca.servicer = s_p.servicer
AND ca.product = s_p.product
AND ca.product_group = s_p.product_group
AND ca.portfolio = s_p.portfolio
AND ca.channel = s_p.channel
FULL OUTER JOIN adhoc_work.Summary_uy s_uy
ON ca.reporting_period = s_uy.reporting_period
AND ca.state = s_uy.state
AND s_p.state = s_uy.state
AND ca.servicer = s_uy.servicer
AND s_p.servicer = s_uy.servicer
AND ca.product = s_uy.product
AND s_p.product = s_uy.product
AND ca.product_group = s_uy.product_group
AND s_p.product_group = s_uy.product_group
AND ca.portfolio = s_uy.portfolio
AND s_p.portfolio = s_uy.portfolio
AND ca.channel = s_uy.channel
AND s_p.channel = s_uy.channel
WHERE COALESCE(ca.reporting_period,s_p.reporting_period,s_uy.reporting_period) BETWEEN DATE_FORMAT(TIMESTAMPADD(MONTH,-13,NOW(3)),'%Y%m%d') AND DATE_FORMAT(NOW(3),'%Y%m%d')
GROUP BY COALESCE(ca.reporting_period,s_p.reporting_period,s_uy.reporting_period)
,COALESCE(ca.state,s_p.state,s_uy.state)
,COALESCE(ca.servicer,s_p.servicer,s_uy.servicer)
,COALESCE(ca.product,s_p.product,s_uy.product)
,COALESCE(ca.product_group,s_p.product_group,s_uy.product_group)
,COALESCE(ca.portfolio,s_p.portfolio,s_uy.portfolio)
,COALESCE(ca.channel,s_p.channel,s_uy.channel)
,ca.gross
,ca.Costs
,ca.commission
,ca.commissionable
,s_p.WAVG_placed_numerator
,s_p.place_balance
,ca.costs_recovered;
Actually, your query doesn't quite do a full outer join, because a condition like this:
ca.state = s_uy.state
requires that ca.state be matched. That is, the outer join is turned to an inner join.
So, to answer your question more theoretically, the simplest method is probably to generate all the rows by using UNION among the the table and then use left join:
FROM (SELECT reporting_period, . . .
FROM adhoc_work.Cash ca
UNION -- on purpose to remove duplicates
SELECT reporting_period, . . .
FROM adhoc_work.Summary_placed
UNION -- on purpose to remove duplicates
SELECT reporting_period, . . .
FROM adhoc_work.Summary_uy
) x LEFT JOIN
adhoc_work.Cash ca
ON x.reporting_period = ca.reporting_period AND
. . . LEFT JOIN
adhoc_work.Summary_placed s_p
ON x.reporting_period = s_p.reporting_period AND
. . . LEFT JOIN
adhoc_work.Summary_uy s_uy
ON x.reporting_period = s_uy.reporting_period AND
. . .
I have a rails join table between 2 models superhero and superpower. Now I have 3 different superpower id and I want all the superheroes which have all the selected superpowers
To do that I'm trying to do the following:
matches = Superhero.all
matches = matches.joins(:superpowers).where('superpowers.id = ?', 17).where('superpowers.id = ?', 12).where('superpowers.id = ?', 6)
But this gives me an empty object even though I have superheroes which have all the given superpowers in my join table
The query generated from the above is:
SELECT "superheroes".* FROM "superheroes" INNER JOIN "superheroes_superpowers" ON "superheroes_superpowers"."superhero_id" = "superheroes"."id" INNER JOIN "superpowers" ON "superpowers"."id" = "superheroes_superpowers"."superpower_id" WHERE (superpowers.id = 17) AND (superpowers.id = 17) AND (superpowers.id = 12) AND (superpowers.id = 6)
So weirdly it tries to check for the superpower with id 17 twice (but it shouldn't affect the result I think) and the rest of the query seems to be correct.
try using an in clause
superpowers_ids = [17,12,6]
matches = Superhero.all
matches = matches.joins(:superpowers).where('superpowers.id in (?)', superpowers_ids)
Superhero.joins(:superpowers).where(superpowers: { id: [17,12,6] } )
This gives the following SQL query (formatted for readibility):
SELECT "superheros".*
FROM "superheros"
INNER JOIN "superhero_superpowers" ON "superhero_superpowers"."superhero_id" = "superheros"."id"
INNER JOIN "superpowers" ON "superpowers"."id" = "superhero_superpowers"."superpower_id"
WHERE "superpowers"."id" IN (17, 12, 6)
There is $this->db_selec_max(); for select max element from row set in select but I want to use max in where. How to use "MAX" in codeigniter where? I want to convert following query in to codeigniter form
My query
SELECT rq_id, rq_plant_4sale_code, rq_serial_number, rq_quantity_requested, rq_requester_farm_id,
rq_fulfiller_farm_id, rqpri_description, rqrem_remark,rqrem_remark_datetime, rq_created_datetime,
plsal_name_botanical, plsal_name_english, pot_code, rqpri_description
FROM (reqn_requisitions)
LEFT JOIN reqn_requisition_priorities ON(rq_priority_rank=rqpri_rank)
LEFT JOIN reqn_requisition_remarks ON(rq_id=rqrem_reqn_id)
LEFT JOIN tukai_plants_4sale ON(rq_plant_4sale_code=plsal_id)
LEFT JOIN tukai_pots ON(plsal_pot_id=pot_id)
WHERE rqrem_remark_datetime IN(SELECT MAX(rqrem_remark_datetime) AS dt FROM reqn_requisition_remarks GROUP BY rqrem_reqn_id ) AND rq_challan_id=0'
I am trying like this
$this->db->select("rq_id, rq_plant_4sale_code, rq_serial_number, rq_quantity_requested, rq_requester_farm_id,
rq_fulfiller_farm_id, rqpri_description, rqrem_remark,rqrem_remark_datetime, rq_created_datetime,
plsal_name_botanical, plsal_name_english, pot_code, rqpri_description ");
$this->db->join('tukai_plants_4sale',
'tukai_plants_4sale.plsal_id = reqn_requisitions.rq_plant_4sale_code','left');
$this->db->join('tukai_pots',
'tukai_pots.pot_id = tukai_plants_4sale.plsal_pot_id','left');
$this->db->join('reqn_requisition_remarks',
'reqn_requisition_remarks.rqrem_reqn_id = reqn_requisitions.rq_id','left');
$this->db->order_by("rq_id","desc");
For complex where clause conditions you can use,
$this->db->where('<where condition here>', NULL, FALSE);
From docs:
$this->db->where() accepts an optional third parameter. If you set it to FALSE, CodeIgniter will not try to protect your field or table names with backticks.
Try below code:
/* Replace table_name with appropriate table names */
$this->db->select("table_name.rq_id, table_name.rq_plant_4sale_code, table_name.rq_serial_number, table_name.rq_quantity_requested, table_name.rq_requester_farm_id,
table_name.rq_fulfiller_farm_id, table_name.rqpri_description, rqrem_remark,table_name.rqrem_remark_datetime, table_name.rq_created_datetime,
table_name.plsal_name_botanical, table_name.plsal_name_english, table_name.pot_code, table_name.rqpri_description ");
$this->db->from('reqn_requisitions');
$this->db->join('reqn_requisition_priorities','reqn_requisitions.rq_priority_rank = reqn_requisition_priorities.rqpri_rank','left');
$this->db->join('reqn_requisition_remarks','reqn_requisition_remarks.rqrem_reqn_id = reqn_requisitions.rq_id','left');
$this->db->join('tukai_plants_4sale','tukai_plants_4sale.plsal_id = reqn_requisitions.rq_plant_4sale_code','left');
$this->db->join('tukai_pots','tukai_pots.pot_id = tukai_plants_4sale.plsal_pot_id','left');
$this->db->where('reqn_requisition_remarks.rqrem_remark_datetime IN(SELECT MAX(rqrem_remark_datetime) AS dt FROM reqn_requisition_remarks GROUP BY rqrem_reqn_id', NULL, FALSE);
$this->db->where('table_name.rq_challan_id', 0);
$this->db->order_by("table_name.rq_id","desc");
$query = $this->db->get();
return $query->result();
An alternative:
If your query (anyhow) cannot be written using CI's Active Record, you can always use a simple method:
$this->db->query('<your SQL query here>');
For example:
$query = $this->db->query('SELECT rq_id, rq_plant_4sale_code, rq_serial_number,rq_quantity_requested, rq_requester_farm_id,rq_fulfiller_farm_id, rqpri_description,rqrem_remark,rqrem_remark_datetime, rq_created_datetime,
plsal_name_botanical, plsal_name_english, pot_code, rqpri_description
FROM (reqn_requisitions)
LEFT JOIN reqn_requisition_priorities ON(rq_priority_rank=rqpri_rank)
LEFT JOIN reqn_requisition_remarks ON(rq_id=rqrem_reqn_id)
LEFT JOIN tukai_plants_4sale ON(rq_plant_4sale_code=plsal_id)
LEFT JOIN tukai_pots ON(plsal_pot_id=pot_id)
WHERE rqrem_remark_datetime IN(SELECT MAX(rqrem_remark_datetime) AS dt FROM reqn_requisition_remarks GROUP BY rqrem_reqn_id ) AND rq_challan_id=0');
return $query->result();
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.