Subquery with order by - mysql

I wrote a query with a subquery and both of them have an order by.
I have a weird behavior, sometimes I don't get back all the rows, sometimes I have 0 rows, but if I run the inner query I have the correct rows always. Is there some limitation about subquery? MySql is version 5.5
thanks a lot
SELECT
*
FROM
(
SELECT
#fakeId := #fakeId + 1 AS fakeId,
#balance := (#balance + traIn.amount) AS balance,
FROM
(SELECT #fakeId := 0, #balance := 0) AS vars,
table1 traIn
INNER JOIN table2 traTypeIn ON traIn._id = traTypeIn.id
INNER JOIN table3 ptfIn ON traIn.ptf_id = ptfIn.id
LEFT JOIN `user` u ON u.id = traIn.user_create_id
LEFT JOIN `user` up ON up.id = traIn.user_update_id
WHERE
<--- a couple of constraints -->
ORDER BY
traIn.date
) AS data
ORDER BY data.fakeId DESC
LIMIT 50;

Why do you don't, on your sub-query, select traIn.date, and after that, select only fakeId, balance
Somethings like that :
SELECT
data.fakeId, data.balance
FROM
(
SELECT
#fakeId := #fakeId + 1 AS fakeId,
#balance := (#balance + traIn.amount) AS balance,
traIn.date as date1
FROM
(SELECT #fakeId := 0, #balance := 0) AS vars,
table1 traIn
INNER JOIN table2 traTypeIn ON traIn._id = traTypeIn.id
INNER JOIN table3 ptfIn ON traIn.ptf_id = ptfIn.id
LEFT JOIN `user` u ON u.id = traIn.user_create_id
LEFT JOIN `user` up ON up.id = traIn.user_update_id
WHERE
<--- a couple of constraints -->
) AS data
ORDER BY data.date1, data.fakeId DESC
LIMIT 50;

Related

Update field in a table with values from another field from another table

I need to update the last 110 values ​​of the descricao_geral table with the last 110 values ​​of the relevo table
I'm doing this:
UPDATE descricao_geral
SET id_relevo_fk = (SELECT id_relevo FROM relevo ORDER BY id_relevo DESC LIMIT 110)
ORDER BY id_descricao DESC
LIMIT 110
The error I've received:
Subquery returns more than 1 row
This is really tricky. You need to join the tables together, but you don't have an appropriate key.
You can use variables to assign a sequential value and then use this for the join:
update descricao_geral g join
(select (#rng := #rng + 1) as rn, g2.id_descricao
from (select g2.* from descricao_geral g2 order by g2.id_descricao desc) g2 cross join
(select #rng := 0) params
limit 110
) g2
on g.id_descricao = g2.id_descricao join
(select (#rnr := #rnr + 1) as rn, r.id_relevo
from (select r.* from relevo r order by r.id_relevo desc) r cross join
(select #rnr := 0) params
) r
on g2.rn = r.rn
set g.id_relevo_fk = r.id_relevo;

Column not found in Select statement inside select statement

Trying to select one row at a time from this query (for example where the rank = 1). However, it doesn't work because "unknown column 'rank'. if i change it to "WHERE id = 1" then it works, but for some reason it doesn't know what rank is even tho it is set
SET #rownum=0;
SELECT #rownum := #rownum + 1 AS rank, id, client, date, time, pickupCity, pickupState
FROM (
SELECT r.id, CONCAT(c.fname, ' ', c.lname) as client, r.date,
LOWER(TIME_FORMAT(r.time, '%l:%i%p')) as time, r.pickupCity, r.pickupState
FROM request r
INNER JOIN client c ON r.client = c.id
INNER JOIN pickup p ON r.id = p.request
INNER JOIN driver d ON d.id = p.driver
WHERE date = '2018-04-18' AND d.id = 1
GROUP BY time
) AS tab
HAVING rank = 1;
In MySQL, you can do this using HAVING:
SELECT #rownum := #rownum + 1 AS rank, id, client, date, time, pickupCity, pickupState
FROM (SELECT r.id, CONCAT(c.fname, ' ', c.lname) as client, r.date,
LOWER(TIME_FORMAT(r.time, '%l:%i%p')) as time, r.pickupCity,
r.pickupState
FROM request r JOIN
client c
ON r.client = c.id JOIN
driver d
ON ?
pickup p
ON d.id = p.driver
WHERE date = '2018-04-18' AND d.id = 1
GROUP BY time
) t CROSS JOIN
(SELECT #rank := 0) params
HAVING rank = 1;
Notes:
The ?? is for the missing JOIN conditions.
I went through the effort of fixing your JOIN syntax. You should go through the effort of learning proper, explicit, standard JOIN syntax.
You can set #rank in the query; you don't need a separate statement.
The GROUP BY makes no sense, because you have many unaggregated columns in the SELECT.
If I had to speculate, the root cause of your problems is the missing JOIN condition, and you've put a lot of effort into working around that.

Get row position in the result?

How use #row_number like position row in result in this SQL:
SELECT s.*,
s2.priority AS `priority`,
#row_number := #row_number := #row_number + 1 AS `top`
FROM (SELECT #row_number := 0) init, `server` s
LEFT JOIN servers_services ss ON (s.id = ss.server_id)
LEFT JOIN service s2 ON (s2.id = ss.service_id)
WHERE s.is_banned = 0
ORDER BY ss.service_id IS NULL, priority DESC
#row_number takes values {1, 12, 89 ...} Why?
I don't have experience with variables in MySQL, so my anser can be wrong.
My guess is: You cross join row numbers with your tables. Then in the WHERE clause you dismiss records, so you are left with only some of the original row numbers.
As to how to solve this, I imagine not to join the undesired records in the first place should help:
FROM (SELECT #row_number := 0) init
JOIN server s ON s.is_banned = 0
LEFT JOIN servers_services ss ON (s.id = ss.server_id)
LEFT JOIN service s2 ON (s2.id = ss.service_id)

mysql perform same calculation for all rows on another table

I have my query determined:
SELECT *
FROM `participation`
LEFT JOIN parties ON parties.id = participation.party_id
WHERE `riding_id` = 10001
AND `election_id` = 41
ORDER BY num_votes DESC
LIMIT 1
This accurately produces the result I want.
The result is the most voted for party.
Now I want to perform this same query on every row of a TABLE ridings
which contains all the riding_id rows. Having some trouble getting it.
I don't want to join the other table - but go through every row and perform the same calculation as above - on each row.
Something like:
SELECT *
FROM `participation`
LEFT JOIN parties ON parties.id = participation.party_id
WHERE `riding_id` = "LOOP ALL riding_id IN ridings TABLE"
AND `election_id` = 41
ORDER BY num_votes DESC
LIMIT 1
Any help would be appreciated.
It is tempting to just use a subquery:
SELECT *
FROM participation LEFT JOIN
parties
ON parties.id = participation.party_id
WHERE riding_id IN (SELECT riding_id FROM ridings) AND
election_id = 41
ORDER BY num_votes DESC
But, you no longer get the top vote getter. You get everything.
Here is a method using variables to get just the top vote getting for each riding_id:
SELECT *
FROM (SELECT *,
(#rn := if(#r = riding_id, #rn + 1,
if(#rn := riding_id, 1, 1)
)
) as seqnum
FROM participation LEFT JOIN
parties
ON parties.id = participation.party_id CROSS JOIN
(SELECT #rn := 0, #r := -1) params
WHERE riding_id IN (SELECT riding_id FROM ridings) AND
election_id = 41
ORDER BY riding_id, num_votes DESC
) pp
WHERE seqnum = 1;

MySQL Query Efficiency - Is there a better way?

I have a query that basically combines tables of actions and selects from them in chronological order while preserving pagination..
Is there a more efficient / better way to do this? The query takes 3 seconds. Not terrible.. but I think there is room for improvement and I will be using it alot..
Thanks!
SELECT
`newsletters_subscribers`.`email`,
`newsletters_subscribers`.`first_name`,
`newsletters_subscribers`.`last_name`,
`newsletters_subscribers`.`id` AS subscriber_id,
COUNT(DISTINCT newsletters_opens.id) AS opens,
COUNT(DISTINCT newsletters_clicks.id) AS clicks,
COUNT(DISTINCT newsletters_forwards.id) AS forwards
FROM `thebookrackqccom_newsletters_subscribers` newsletters_subscribers
LEFT JOIN
`thebookrackqccom_newsletters_opens` newsletters_opens
ON `newsletters_opens`.`subscriber_id` = `newsletters_subscribers`.`id`
AND newsletters_opens.newsletter_id = 1
LEFT JOIN
`thebookrackqccom_newsletters_clicks` newsletters_clicks
ON `newsletters_clicks`.`subscriber_id` = `newsletters_subscribers`.`id`
AND newsletters_clicks.newsletter_id = 1
LEFT JOIN
`thebookrackqccom_newsletters_forwards` newsletters_forwards
ON `newsletters_forwards`.`subscriber_id` = `newsletters_subscribers`.`id`
AND newsletters_forwards.newsletter_id = 1
WHERE
( newsletters_opens.id IS NOT NULL
OR newsletters_clicks.id IS NOT NULL
OR newsletters_forwards.id IS NOT NULL )
GROUP BY
`newsletters_subscribers`.`id`
ORDER BY
`newsletters_subscribers`.`email` ASC
LIMIT 25
What you need is indexes that the query can use. A compound index on (newsletter_id, subscribe_id) on each one of the three tables would help.
You can also rewrite the query like this:
SELECT
s.email,
s.first_name,
s.last_name,
s.id AS subscriber_id,
COALESCE(o.opens, 0) AS opens,
COALESCE(c.clicks, 0) AS clicks,
COALESCE(f.forwards, 0) AS forwards
FROM thebookrackqccom_newsletters_subscribers AS s
LEFT JOIN
( SELECT subscriber_id,
COUNT(*) AS opens
FROM thebookrackqccom_newsletters_opens
WHERE newsletters_opens.newsletter_id = 1
) AS o ON o.subscriber_id = s.id
LEFT JOIN
( SELECT subscriber_id,
COUNT(*) AS clicks
FROM thebookrackqccom_newsletters_clicks
WHERE newsletter_id = 1
) AS c ON c.subscriber_id = s.id
LEFT JOIN
( SELECT subscriber_id,
COUNT(*) AS forwards
FROM thebookrackqccom_newsletters_forwards
WHERE newsletter_id = 1
) AS f ON f.subscriber_id = s.id
WHERE ( o.subscriber_id IS NOT NULL
OR c.subscriber_id IS NOT NULL
OR f.subscriber_id IS NOT NULL )
ORDER BY
s.email ASC
LIMIT 25
Try this Query i hope you get a better execution time
QUERY
SELECT
`newsletters_subscribers`.`email`,
`newsletters_subscribers`.`first_name`,
`newsletters_subscribers`.`last_name`,
`newsletters_subscribers`.`id` AS subscriber_id,
#nopen := coalesce( N_OPEN.NOPENIDCOUNT, 000000 ) as opens,
#nclick := coalesce( N_CLICK.NCLICKIDCOUNT, 000000 ) as clicks,
#nfwd := coalesce( N_FWD.NFWDIDCOUNT, 000000 ) as forwards
FROM
(select #nopen := 0,#nclick := 0,#nfwd :=0) sqlvars,
`thebookrackqccom_newsletters_subscribers` AS newsletters_subscribers
LEFT JOIN (SELECT `newsletters_opens`.`subscriber_id`,
COUNT(newsletters_opens.id) AS NOPENIDCOUNT
FROM `thebookrackqccom_newsletters_opens` AS newsletters_opens
WHERE newsletters_opens.newsletter_id = 1) AS N_OPEN
ON N_OPEN.subscriber_id = `newsletters_subscribers`.`id`
LEFT JOIN (SELECT `newsletters_clicks`.`subscriber_id`,
COUNT(newsletters_clicks.id) AS NCLICKIDCOUNT
FROM `thebookrackqccom_newsletters_clicks` AS newsletters_clicks
WHERE newsletters_clicks.newsletter_id = 1) AS N_CLICK
ON N_CLICK.subscriber_id = `newsletters_subscribers`.`id`
LEFT JOIN (SELECT `newsletters_forwards`.`subscriber_id`,
COUNT(newsletters_forwards.id) AS NFWDIDCOUNT
FROM `thebookrackqccom_newsletters_forwards` AS newsletters_forwards
WHERE newsletters_forwards.newsletter_id = 1) AS N_FWD
ON N_FWD.subscriber_id = `newsletters_subscribers`.`id`
GROUP BY `newsletters_subscribers`.`id`
ORDER BY `newsletters_subscribers`.`email` ASC
LIMIT 25