MySQL - sort results by total time - php

i have three tables( runners, stages and time)
Runners table:
+--+----+
|id|name|
+--+----+
|1 |Karl|
+--+----+
|2 |Lou |
+--+----+
Stage Table:
+--+-----+-----+---+
|id|name |order|end|
+--+-----+-----+---+
|1 |start| 1 | 0 |
+--+-----+-----+---+
|2 |bike | 2 | 0 |
+--+-----+-----+---+
|3 |run | 3 | 0 |
+--+-----+-----+---+
|4 |end | 4 | 1 |
+--+-----+-----+---+
Runners data(time) Table:
+------+-----+-----+
|runner|stage|time |
+------+-----+-----+
| 1 | 1 |10:00|
+------+-----+-----+
| 1 | 2 |10:30|
+------+-----+-----+
| 1 | 3 |11:00|
+------+-----+-----+
| 2 | 1 |10:00|
+------+-----+-----+
| 2 | 2 |10:43|
+------+-----+-----+
| 2 | 3 |11:56|
+------+-----+-----+
| 1 | 4 |12:14|
+------+-----+-----+
| 2 | 4 |12:42|
+------+-----+-----+
Well ... then what I want now is to get the results as follows( order by total time ):
+------+-----+-----+-----+-----+----------+
|runner|start|bike |run | end | Total |
+------+-----+-----+-----+-----+----------+
| Karl |10:00|10:30|11:00|12:14| 01:44:00 | <--- FIRST( one hour)
+------+-----+-----+-----+-----+----------+
| Lou |10:30|10:30|11:56|12:42| 02:12:00 | <--- SECONDS( two hours )
+------+-----+-----+-----+-----+----------+
Have any idea how I can accomplish this?
Greetings!

the following should work (times are in seconds, not in HH:MM:SS)
select r.name, rd_start.time as start, rd_bike.time as bike, rd_run.time as run, rd_end.time as end, from runner as r, rd_start.time+rd_bike.time+rd_run.time+rd_end.time as total
inner join runnerdata as rd_start on r.id=rd_start.runner and rd_start.stage=1
inner join runnerdata as rd_bike on r.id=rd_bike.runner and rd_start.stage=2
inner join runnerdata as rd_run on r.id=rd_run.runner and rd_start.stage=3
inner join runnerdata as rd_end on r.id=rd_end.runner and rd_start.stage=4
order by (rd_start.time+rd_bike.time+rd_run.time+rd_end.time)
(If you post the create tables or even better use this tool: http://sqlfiddle.com/ it would make it easier for us to test our statements)

The query would look something like this but the method for calculating the total depends on the data type of the time.
select runners.name as runner, starttime.time as start, biketime.time as bike, runtime.time as run, endtime.time as end, endtime.time - starttime.time as Total
from runners
inner join time as starttime on runners.id = starttime.runner
inner join stages as startstages on starttime.stage = startstages.id and startstages.name = 'start'
inner join time as biketime on runners.id = biketime.runner
inner join stages as bikestages on biketime.stage = bikestages.id and bikestages.name = 'bike'
inner join time as runtime on runners.id = runtime.runner
inner join stages as runstages on runtime.stage = runstages.id and runstages.name = 'run'
inner join time as endtime on runners.id = endtime.runner
inner join stages as endstages on endtime.stage = endstages.id and endstages.name = 'end'
order by endtime.time - starttime.time

This requires a join and then conditional aggregation. The final column uses timediff() to subtract the two times:
select r.name,
max(case when rt.stage = 1 then rt.time end) as start,
max(case when rt.stage = 2 then rt.time end) as walk,
max(case when rt.stage = 3 then rt.time end) as bike,
max(case when rt.stage = 4 then rt.time end) as end,
timediff(max(case when rt.stage = 4 then rt.time end),
max(case when rt.stage = 1 then rt.time end)
) as TotalTime
from RunnersTime rt join
Runners r
on rt.runner = r.id
group by r.id
order by TotalTime;
Note that the column names are fixed, so the stages table is not used. Making them dynamic would make the query much more complicated.

You would probably need to do a lot of inner joining, subquerying, and comparing this time vs. that time if you want to go with that schema, and it really won't be pretty. Alternatively if your stages are fixed you could simplify to one table with each column as a stage. If the number and names of stages need to vary (for whatever reason) then I'd suggest storing a start time and end time in your runners date/time table.
If your stages are fixed then getting the result you are looking for straight out of the database will be easy. If the stages can vary (depending on your site users configuring stages for example) then you'll want to cross-tab your data in PHP or look at this SO question if you insist on doing it in the database (which I'd discourage).

Related

Joining a calendar table to a sales table to get total sales for every day in a specified range

I have a 'sales' table called phpbb_sold which records each 'sale' as a row.
I am able to use a WHERE clause with the uitemid field to select one particular item in the sales records, as seen below:
SELECT uitemid, locktime, migrated_sold FROM phpbb_sold WHERE uitemid=342;
+---------+------------+---------------+
| uitemid | locktime | migrated_sold |
+---------+------------+---------------+
| 342 | 1632523854 | 1 |
| 342 | 1634239244 | 1 |
| 342 | 1634240072 | 1 |
| 342 | 1636367271 | 1 |
+---------+------------+---------------+
uitemid = number that identifies this as a sale of X item. locktime = UNIX timestamp that shows the datetime that the item was sold. migrated_sold = the quantity of the item sold. So this is nice, I have a table that keeps a record of each sale as it happens.
What I want to achieve though, is a record of the total number of sales of this item type, for each day in a 6 month period spanning back from the current date, and including each day regardless of whether a sale was made or not. So the desired output of my query would be:
SELECT (the query I want goes here) and returns the following rows...;
+------------+------------+
| caldate | sold_total |
+------------+------------+
| 2021-09-23 | 2 |
| 2021-09-24 | 0 |
| 2021-09-25 | 1 |
| 2021-09-26 | 0 |
| 2021-09-27 | 0 |
| 2021-09-28 | 1 |
+------------+------------+
Note that each day is included as a row in the results, even where the sales total for that day is 0. I read that to do this, I would be required to create a calendar table with one column and all the days I want as rows, so I went ahead and did that:
SELECT caldate FROM phpbb_calendar;
+------------+
| caldate |
+------------+
| 2021-09-23 |
| 2021-09-24 |
| 2021-09-25 |
| 2021-09-26 |
| 2021-09-27 |
| 2021-09-28 |
+------------+
Now all that remains is for me to make the query. I need to somehow return all the rows from the phpbb_calendar table, joining the data from sum() (?) of the total migrated_sold for those days where exists, and a 0 where no sales took place.
I anticipated some issues with the UNIX timestamp, but it's okay because I am able to get caldate and locktime fields to be the same format by using from_unixtime(locktime, '%Y-%m-%d'), so both dates will be in the YYYY-MM-DD format for comparison.
Please could someone help me with this. I've gotten so close every time but it seems that everyone else's request is only slightly different from mine, so existing questions and answers have not been able to satisfy my requirements.
End goal is to use a JS chart library (AnyChart) to show a line graph of the number of sales of the item over time. But to get there, I first need to provide it with the query necessary for it to display that data.
Thanks
Update
Using this query:
SELECT c.caldate, u.uitemid, sum(v.migrated_sold) as total_sales
from phpbb_calendar c cross join
(select distinct uitemid from phpbb_sold) u left join
phpbb_sold v
on c.caldate = from_unixtime(v.locktime, '%Y-%m-%d') WHERE u.uitemid = 39 and c.caldate <= curdate() GROUP BY c.caldate ORDER BY c.caldate;
Returns:
But as you can see, it's just tallying up the total number of sales ever made or something - its clearly incrementing in a way I don't understand.
I don't want it to do that - I want it to count the number of total sales on each day individually. The results should look like this:
So that what is returned is basically a 'histogram' of sales, if any occurred, including 'empty' days where there were no sales (so these empty days must still be returned as rows).
SELECT c.caldate, u.uitemid, COALESCE(SUM(v.migrated_sold), 0) AS total_sales
FROM phpbb_calendar c
CROSS JOIN (SELECT DISTINCT uitemid FROM phpbb_sold WHERE uitemid = 37) u
LEFT JOIN phpbb_sold v
ON v.locktime BETWEEN UNIX_TIMESTAMP(TIMESTAMP(c.caldate)) AND UNIX_TIMESTAMP(TIMESTAMP(c.caldate, '23:59:59'))
AND u.uitemid = v.uitemid
WHERE c.caldate BETWEEN CURDATE() - INTERVAL 6 MONTH AND CURDATE()
GROUP BY c.caldate, u.uitemid
ORDER BY c.caldate;
N.B. I have changed your join to use the unix_timestamp as it should be more efficient and it can use any existing index on locktime
check this out:
select id, d, sum(s) from (
select U.id, d, 0 s from (
select adddate(current_date(),-rows.r) d from (
select (#row_number := #row_number + 1) r
from information_schema.columns,
(SELECT #row_number := 0) AS x
limit 200
) rows
) dates,
(SELECT distinct uitemid id FROM `phpbb_sold`) U
where d > adddate(current_date(), interval -6 month)
union
select uitemid, date(from_unixtime(locktime)),sum(migrated_sold)
from `phpbb_sold`
group by uitemid, date(from_unixtime(locktime))
) sales_union
group by id, d
order by id, d;
see dbfiddle
no need for calendar table

Complex query combining

First of all, thank you for reading my problem. I am very thankful for the people in the community helping others learn more about coding. As this SQL and PHP is part of my hobby, I am limited by Google and fora where I can find answers to my questions. Unfortunately, I can't find a good answer for a problem encountered.
What am I trying to do?
I run a website where you can note your kilometers and liters you filled your car and see your statistics. I want to do a big search in MySQL with a query. I know how to get the results in multiple queries (3 to be exact), but I need it to be in one single query.
What does my table look look like?
For an example I am using this table to make the problem more visual, it's named 'fillings' for now.
+---------+---------+------------+--------+--------+------------+
| tank_id | user_id | kilometers | liters | car_id | date |
+---------+---------+------------+--------+--------+------------+
| 1 | 2 | 450 | 20 | 2 | 2017-11-01 |
+---------+---------+------------+--------+--------+------------+
| 2 | 1 | 500 | 30 | 1 | 2017-12-15 |
+---------+---------+------------+--------+--------+------------+
| 3 | 2 | 490 | 25 | 2 | 2017-11-05 |
+---------+---------+------------+--------+--------+------------+
| 4 | 3 | 260 | 19 | 3 | 2017-11-07 |
+---------+---------+------------+--------+--------+------------+
| 5 | 3 | 610 | 30 | 3 | 2017-12-03 |
+---------+---------+------------+--------+--------+------------+
| 6 | 3 | 100 | 4 | 3 | 2017-12-07 |
+---------+---------+------------+--------+--------+------------+
This is a basic idea of my main table where all the fill-ups are being registrated. In reality someone can have multiple cars, but for now let's asume that a user only has one car.
What are the SQL queries?
The query that I want to make should have this result:
+---------+----------------------+---------------------+
| user_id | consumption november | consumption overall |
+---------+----------------------+---------------------+
| 2 | 20,9 | 20,9 |
+---------+----------------------+---------------------+
| 1 | | 16,7 |
+---------+----------------------+---------------------+
| 3 | 13,7 | 18,3 |
+---------+----------------------+---------------------+
As you can see, the fillings of november are taking and a consumption is being calculated. Also, an overall consumption is being calculated of all fillings from a certain type of user. I know how to make this result, devided in two queries. That's:
SELECT user_id, SUM(kilometers) / SUM(liters) as consumption overall
FROM fillings
GROUP BY user_id
And also the query:
SELECT user_id, SUM(kilometers) / SUM(liters) as consumption november
FROM fillings
WHERE 'date'
BETWEEN '2017-11-01' AND '2017-11-31'
GROUP BY user_id
So right now I want to combine the queries into one, so that I can get the result that I want. Note that in the example, someone can have a null consumption in a month, because hé or she did not fill up their car in that month.
I've looked into the options of UNION and JOIN but I can't seem to find a way to make this working.
I hope everything is clear, and if not, don't hesitate to ask and I will explain in further detail.
Thanks in advance.
Since it is possible that the records are not in range within the month, a LEFT JOIN is recommended for the date specific query:
SELECT
t1.user_id, t2.consumption_november, t1.consumption_overall
FROM (
SELECT user_id, SUM(kilometers) / SUM(liters) as consumption_overall
FROM fillings
GROUP BY user_id
) t1
LEFT JOIN
(
SELECT user_id, SUM(kilometers) / SUM(liters) as consumption_november
FROM fillings
WHERE `date` BETWEEN '2017-11-01' AND '2017-11-31'
GROUP BY user_id
) t2
ON t1.user_id = t2.user_id;
http://sqlfiddle.com/#!9/3fdce84/16
Just use conditional aggregation:
SELECT user_id,
(SUM(CASE WHEN date >= '2017-11-01' AND date < '2017-12-01'
THEN kilometers ELSE 0
END) /
SUM(CASE WHEN date >= '2017-11-01' AND date < '2017-12-01'
THEN liters
END)
) as consumption_november,
SUM(kilometers) / SUM(liters) as consumption_overall
FROM fillings
GROUP BY user_id
You can try something like
SELECT t1.user_id,
t1.consumption_overall as consumption overall,
t2.consumption_november as consumption november
FROM (
SELECT user_id, SUM(kilometers) / SUM(liters) as consumption_overall
FROM fillings
GROUP BY user_id
) as t1, (
SELECT user_id, SUM(kilometers) / SUM(liters) as consumption_november
FROM fillings
WHERE 'date'
BETWEEN '2017-11-01' AND '2017-11-31'
GROUP BY user_id
) as t2
WHERE t1.user_id = t2.user_id
It will take the results of you two queries and put them in the same table.
For the extended answer (to your question in my first answer, since it's too long to leave as a comment), use :
SELECT
t1.user_id, t2.consumption_november, t3.consumption_q, t1.consumption_overall
FROM (
SELECT user_id, SUM(kilometers) / SUM(liters) as consumption_overall
FROM fillings
GROUP BY user_id
) t1
LEFT JOIN
(
SELECT user_id, SUM(kilometers) / SUM(liters) as consumption_november
FROM fillings
WHERE [date] BETWEEN '2017-11-01' AND '2017-11-31'
GROUP BY user_id
) t2
ON t1.user_id = t2.user_id
LEFT JOIN
(
SELECT user_id, SUM(kilometers) / SUM(liters) as consumption_q
FROM fillings
WHERE [date] BETWEEN '2017-08-01' AND '2017-11-31'
GROUP BY user_id
) t3
ON t1.user_id = t3.user_id;
for a subsequent left join, just remove the semicolon from the final left join and extend the pattern, and add the new field in the SELECT clause.

Table inside of another

I want to plan my trips publicly so other people can join me. So, I have set-up an PHP site.
I have this tables:
trips:
+----+---------+------------+------------+-------------------------+
| id | title | date_start | date_end | marker_adress |
+----+---------+------------+------------+-------------------------+
| 1 | Berlin | 2015-07-10 | 2015-07-11 | Potsdamer Platz, Berlin |
| 2 | Hamburg | 2015-07-16 | 2015-07-18 | Jungfernstieg, Hamburg |
+----+---------+------------+------------+-------------------------+
fellows:
+----+---------+---------------+
| id | trip_id | twittername |
+----+---------+---------------+
| 1 | 1 | prtyengopls |
| 2 | 1 | itobi_yt |
| 3 | 1 | jessisadancer |
| 4 | 2 | jessisadancer |
| 5 | 2 | woelfch3n |
+----+---------+---------------+
For displaying sake, I want to query them in one query. How can I query the database so I have something like this? (I know, it's JSON but it shows the structure very well.)
{
"id": 1,
"date_start": "2015-07-10",
"date_end": "2015-07-11",
"marker_adress": "Potsdamer Platz, Berlin",
"fellows": [
{
"id": 1,
"twittername": "prtyengopls"
},
{
"id": 2,
"twittername": "itobi_yt"
},
{
"id": 3,
"twittername": "jessisadancer"
}
]
}
First you have to use a LEFT JOIN like this:
SELECT
t.id AS tripID,
t.title AS title,
t.date_start AS dateStart,
t.date_end AS dateEnd,
t.marker_address AS markerAddress,
GROUP_CONCAT(DISTINCT CAST(f.id AS CHAR)) AS fellowID,
GROUP_CONCAT(DISTINCT CAST(f.twittername AS CHAR)) AS twitterName
FROM trips t LEFT JOIN fellows f ON t.id = f.trip_id
GROUP BY t.id
By using this you will get a single row for each trip and you can loop over fellowID and twitterName for each row, as it will be comma delimited list like this:
fellowID: 1,2,3
twitterName: prtyengopls,itobi_yt,jessisadancer
Edit 1: I got a new column to trips called checked which is a boolean.
Could you update your query, so only trips that have this boolean
toggled on are displayed?
SELECT
t.id AS tripID,
t.title AS title,
t.date_start AS dateStart,
t.date_end AS dateEnd,
t.marker_address AS markerAddress,
GROUP_CONCAT(DISTINCT CAST(f.id AS CHAR)) AS fellowID,
GROUP_CONCAT(DISTINCT CAST(f.twittername AS CHAR)) AS twitterName
FROM trips t INNER JOIN fellows f
ON t.id = f.trip_id AND t.checked = 1
GROUP BY t.id
I don't think it's possible like you expected in SQL. Just to answer your question and show you the problem: you have to use a join (left, inner or something ... depends of your database structure; I always prefer left joins if possible) to get all information in just one query:
SELECT * FROM trips t LEFT JOIN fellows f on t.id = f.trip_id WHERE t.id = 1;
But you always will get the trip information with every row, and for that you have to process it afterwards. You will never able to select such a nested structure, you will always get a flat one.
So I would recommend to split it into two queries like this:
SELECT * FROM trips WHERE id = 1;
SELECT * FROM fellows WHERE trip_id = 1;
You will have to process the information afterwards too, but you just select the wanted information from your database.
Hope that helps.

Mysql - join 2 queries with limit

Im not very familiar with using 'join' in queries. I really tried solving this by my own, but it seems to be too hard.
I got 2 Tables:
Table 'users':
+-----------------+-----------------+
| member | online |
+-----------------+-----------------+
| mahran | 1 |
| peter | 1 |
| Jen | 1 |
| Steve | 0 |
+-----------------+-----------------+
Table 'tickets'
+-----------------+----------------+----------------+
| name | category | time |
+-----------------+----------------+----------------+
| mahran | silver | 1 |
| peter | blue | 1 |
| mahran | blue | 2 |
| peter | red | 3 |
| peter | green | 2 |
| Jen | silver | 1 |
+-----------------+----------------+----------------+
The chellange:
I need each member (users.member) who's online (users.online). The next thing is to get the category for each member (user.member = tickets.name) with the highest time (probably ORDER BY time DESC LIMIT 1).
So, for example:
Peter is online. Peters highest time is 3 at the position of category=red. So I want peter to show up in the result with his category 'red'. Mahran would show up with blue. Jen would get silver. And steve would be left out because he's not online.
I hope this was clear. In general I know how the queries would look like but theres no chance for me merging them together.
What needs to be merged:
SELECT member FROM users WHERE online = 1;
|
v for each member
SELECT category FROM tickets WHERE name=users.member ORDER BY time DESC.
So, any ideas how to solve this?
Here is a fiddle with a not working query: Click
You can do this easily with a correlated subquery:
select u.member,
(select t.category
from tickets t
where t.name = u.member
order by t.time desc
limit 1
) as MostRecentCategory
from users u
where u.online = 1;
This can make use of the following indexes: users(online, member) and ticket(member, time, category).
Here is the query you're looking for:
SELECT U.member
,T.category
FROM users U
INNER JOIN tickets T ON T.name = U.member
INNER JOIN (SELECT T2.name
,MAX(T2.time) AS [maxTime]
FROM tickets T2
GROUP BY T2.name) AS M ON M.name = T.name
AND M.maxTime = T.time
WHERE U.online = 1
The use of [name] to join the two tables is not a good practice, it's much better to use keys instead. But my query is just here to help you understanding the process of jointure.
Hope this will help you.
If i understand you correctly
SELECT DISTINCT users.member, tickets.category FROM tickets JOIN users ON users.member = tickets.name WHERE users.online = 1 ORDER BY tickets.time DESC
Can you make sql fiddle?
USE DISTINCT
stackoverflow.com/questions/11704012/mysql-distinct-join
try this
SELECT DISTINCT User.member,Ticket.category FROM users AS USER
INNER JOIN tickets AS Ticket ON (User.member = Ticket.name)
WHERE User.online = 1;
Sorry, but peter seems to be RED, It's time is 3. Don't you?
Depending on table definition, is not guaranteed to have one only result for each user.
For example, if peter has time 3 in two categories, you can get one different category depending of the SQL sorting method.
To be sure, tickets.Category and tickets.time must be in a unique key (both toghether, not a unike key for each field)
Assuming that, the Query could be this.
select t2.name, t2.category
from
tickets t2
INNER JOIN (Select
u.member, max(time)
from users u, tickets t
where
u.member = t.name
and u.online = 1
group by u.member
) as usermaxtime on t2.name = usermaxtime.member;

Select row in which the sum of the times the same value came up is less than X

this one been puzzling me for a couple of searching hours.
So I have a campaign table and a vendor Table. The vendor might have several campaigns.
I want to select all campaigns if the vendor has enough credits.
Problem is I don't know how many campaigns are going to be selected from the same vendor which means that the vendor might still have credits for two campaigns but not for the rest of them.
Example
tblvendors
+---------+------------+---------------+
|vendorId | vendorName | vendorCredits |
+---------+------------+---------------+
| 1 | a | 5 |
| 2 | b | 100 |
+---------+------------+---------------+
tblproducts
+-----------+---------------+------------+
| productId | productName | vendorId |
+-----------+---------------+------------+
| 1 | c | 1 |
| 2 | e | 2 |
| 3 | f | 1 |
| 4 | g | 1 |
| 5 | h | 1 |
+-----------+---------------+------------+
tblcampaigns
+------------+---------------+------------+
| campaignId | productId | vendorId |
+------------+---------------+------------+
| 1 | 1 | 1 |
| 2 | 2 | 2 |
| 3 | 3 | 1 |
| 4 | 4 | 1 |
| 5 | 5 | 1 |
+------------+---------------+------------+
Now considering that everytime a row is selected the vendor looses 2 credits since vendor 'a' only has 5 credits left only campaigns 1 2 and 3 should be returned.
My current Query is this:
SET #maxCampaignId = (SELECT MAX(campaignId) FROM tblCampaigns);
SELECT
#maxCampaignId,
t0.campaignId,
t0.productId,
productName,
productDescription,
productImage,
(CASE WHEN campaignId > (SELECT configValue FROM tblconfiguration WHERE configKey = 'lastHomeCampaignId')
THEN campaignId ELSE campaignId + #maxCampaignId END) AS orderField
FROM tblcampaigns AS t0
INNER JOIN tblproducts AS t1 ON t0.productId = t1.productId
INNER JOIN tblvendors AS t2 ON t1.vendorId = t2.vendorId
WHERE
campaignType = 'homeFeature' AND
t0.isActive = 1 AND
t2.vendorCredits > (SELECT configValue FROM tblconfiguration WHERE configKey = 'campaignHomeFeatureCost' LIMIT 1)
ORDER BY orderField ASC
LIMIT 4
The problem as you can see is int the line that compares the vendorCredits. Obviously as is the query selects more campaigns than the vendor can afford.
I wanted to avoid doing this in PHP as I think it should be possible to do this straight out of the database.
Check this post, it may help - group by and having clauses. I'll try to do some test later
Using COUNT(*) in the WHERE clause
UPDATE:
select t2.vendorId, vendorCredits from tblcampaigns AS t0 JOIN tblproducts AS t1 ON t0.productId = t1.productId JOIN tblvendors AS t2 ON t1.vendorId = t2.vendorId group by t2.vendorId having t2.vendorCredits = count(t2.vendorId)
If I correctly understood the question: This query will select all vendors having more campains than credits.
Ok found it.
Thanks to this post: How do I limit the number of rows per field value in SQL?
What I did was Selecting the rows I wanted in the order I wanted as a subquery and its respective row number so that I could reorder it back in the end.
Then I made a second subquery ordered by the vendorId so that I could count the number of times it turned up and returning the row_count to the main query.
Finally in the main query I reordered it back to the row number in the deepest subquery but now I have the value I wanted to compare which is the value of credits per row * the current row number for a particular vendor.
Anyways maybe the code is cleared and here it goes:
SET #creditsCost = (SELECT configValue FROM tblconfiguration WHERE configKey = 'campaignHomeFeatureCost' LIMIT 1);
SET #maxCampaignId = (SELECT MAX(campaignId) FROM tblCampaigns);
SET #curRow = 0;
SELECT * FROM
(
SELECT *,
#num := if(#first_column = vendorId, #num:= #num + 1, 1) as row_num,
#first_column:=vendorId as c
FROM
(SELECT
#curRow := #curRow + 1 AS row_number,
#maxCampaignId,
t0.campaignId,
t0.productId,
t2.vendorId,
t2.vendorCredits,
productName,
productDescription,
productImage,
(CASE WHEN campaignId > (SELECT configValue FROM tblconfiguration WHERE configKey = 'lastHomeCampaignId')
THEN campaignId ELSE campaignId + #maxCampaignId END) AS orderField
FROM tblcampaigns AS t0
INNER JOIN tblproducts AS t1 ON t0.productId = t1.productId
INNER JOIN tblvendors AS t2 ON t1.vendorId = t2.vendorId
WHERE
campaignType = 'homeFeature' AND
t0.isActive = 1
ORDER BY orderField ASC) AS filteredCampaigns
ORDER BY vendorId
) AS creditAllowedCampaigns
WHERE
row_num * #creditsCost <= vendorCredits
ORDER BY row_number
Anyhow I still appreciate Who took the time to answer and try to help, and will be listening to future comments since I think this is not the best way performance wise.

Categories