Order by day_of_week in MySQL - mysql

How can I order the mysql result by varchar column that contains day of week name?
Note that MONDAY should goes first, not SUNDAY.

Either redesign the column as suggested by Williham Totland, or do some string parsing to get a date representation.
If the column only contains the day of week, then you could do this:
ORDER BY FIELD(<fieldname>, 'MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', 'FRIDAY', 'SATURDAY', 'SUNDAY');

Why not this?
ORDER BY (
CASE DAYOFWEEK(dateField)
WHEN 1 THEN 7 ELSE DAYOFWEEK(dateField)
END
)
I believe this orders Monday to Sunday...

I'm thinking that short of redesigning the column to use an enum instead, there's not a lot to be done for it, apart from sorting the results after you've gotten them out.
Edit: A dirty hack is of course to add another table with id:weekday pairs and using joins or select in selects to fake an enum.

... ORDER BY date_format(order_date, '%w') = 0, date_format(order_date, '%w') ;

This looks messy but still works and seems more generic:
select day,
case day
when 'monday' then 1
when 'tuesday' then 2
when 'wednesday' then 3
when 'thursday' then 4
when 'friday' then 5
when 'saturday' then 6
when 'sunday' then 7
end as day_nr from test order by day_nr;
Using if is even more generic and messier:
select id, day,
if(day = 'monday',1,
if(day = 'tuesday',2,
if(day = 'wednesday',3,
if(day = 'thursday',4,
if(day = 'friday',5,
if(day = 'saturday',6,7)
)
)
)
)
) as day_nr from test order by day_nr;
You can also hide the details of conversion from name to int in stored procedure.

I realise that this is an old thread, but as it comes to the top of google for certain search times I will use it to share my approach.
I wanted the same result as the original question, but in addition I wanted the ordering of the results starting from the current day of the week and then progressing through the rest of the days.
I created a separate table, in which the days were listed over a fortnight, so that no matter which day you started from you could run through a sequence of 7 days.
CREATE TABLE IF NOT EXISTS `Weekdays` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=15 ;
INSERT INTO `Weekdays` (`id`, `name`) VALUES
(1, 'Monday'),
(2, 'Tuesday'),
(3, 'Wednesday'),
(4, 'Thursday'),
(5, 'Friday'),
(6, 'Saturday'),
(7, 'Sunday'),
(8, 'Monday'),
(9, 'Tuesday'),
(10, 'Wednesday'),
(11, 'Thursday'),
(12, 'Friday'),
(13, 'Saturday'),
(14, 'Sunday');
I then ran the query with a variable that determined the start point in sequence and used a join to get the order number for the days. For example to start the listing at Wednesday, I do the following:
SELECT #startnum := MIN(id) FROM Weekdays WHERE name='Wednesday';
SELECT * FROM Events INNER JOIN ( SELECT id as weekdaynum, name as dayname FROM Weekdays WHERE id>(#startnum-1) AND id<(#startnum+7) ) AS s2 ON s2.dayname=Events.day ORDER BY weekdaynum;
I hope this helps someone who stumbles onto this post.

Found another way, your can reverse order bye week
ORDER BY date_format(date_name, '%w') DESC;

Another way would be to create another table with those days and an int to order them by, join that table when searching, and order by it. Of course, joining on a varchar is not recommended.
Table DaysOfWeek
id | day
--------------------
1 | Monday
2 | Tuesday
3 | Wednesday
4 | Thursday
5 | Friday
6 | Saturday
SELECT * FROM WhateverTable
LEFT JOIN DaysOFWeek on DaysOFWeek.day = WhateverTable.dayColumn
ORDER BY DaysOfWeek.id
(Apologies if that's not correct; I've been stuck with SQL server recently)
Again, this is NOT recommended, but if you cannot alter the data you've already got... This will also work if there are non-standard values in the dayColumn field.

Found another way that works for me:
SELECT LAST_NAME, HIRE_DATE, TO_CHAR(HIRE_DATE, 'fmDAY') as 'Day' FROM EMPLOYEES
ORDER BY TO_CHAR(HIRE_DATE, 'd');
Hope it helps

In my case, since the days can be registered in several languages, to get the correct order I do like this according to Glen Solsberry:
....
....
ORDER BY
FIELD(<fieldname>, 'MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', 'FRIDAY', 'SATURDAY', 'SUNDAY'),
FIELD(<fieldname>, 'LUNDI', 'MARDI', 'MERCREDI', 'JEUDI', 'VENDREDI', 'SAMEDI', 'DIMANCHE'),
FIELD(<fieldname>, 'LUNES', 'MARTES', 'MIERCOLES', 'JUEVES', 'VIERNES', 'SABADO', 'DOMINGO'),
FIELD(<fieldname>, 'MONTAGE', 'DIENSTAG', 'MITTWOCH', 'DENNERSTAG', 'FREITAG', 'SAMSTAG', 'SONNTAG')
;
Do not forget that, <fieldname> is the name of the date column in question in your case.

I saw that ...WHEN 1 THEN 7... was posted but it should be WHEN 1 THEN 8.
So...
ORDER BY (
CASE DATEPART(DW, yourdatefield)
WHEN 1 THEN 8 ELSE DATEPART(DW, yourdatefield)
END
)
Otherwise Sunday may come before Saturday because both Sunday and Saturday would equal 7. By setting Sunday to 8, it ensures it comes after Saturday.

If you try this, it should work:
SELECT ename, TO_CHAR(hiredate, 'fmDay') as "Day"
FROM my_table
ORDER BY MOD(TO_CHAR(hiredate, 'D') + 5, 7)

Related

Find the user who increased their hours streamed from the previous calendar month

This table is a "heartbeat" tracking event where one row is genereated each minute for each streamer while that streamer is live. If a streamer is live for 60 minutes, 60 rows would be generated in this table
Create Table minute_streamed
(
time_minute datetime ,
username varchar(50) ,
category varchar(50) ,
concurrent_viewers int
)
Insert into minute_streamed values ('2020-03-18 12:00:00', 'alex','Fornite',125) ;
Insert into minute_streamed values ('2020-03-18 12:01:00', 'alex','Fornite',130) ;
Insert into minute_streamed values ('2020-03-19 15:30:00', 'jamie','Just Chatting',13) ;
Insert into minute_streamed values ('2020-03-19 15:31:00', 'jamie','Food & Drink',15) ;
Insert into minute_streamed values ('2020-03-20 10:30:00', 'rick','Call of Duty: Black Ops',150) ;
Insert into minute_streamed values ('2020-03-20 10:31:00', 'rick','Call of Duty: Modern Warfare',120) ;
Insert into minute_streamed values ('2020-04-21 09:30:00', 'rick','Fornite',120) ;
Insert into minute_streamed values ('2020-04-20 10:31:00', 'rick','Call of Duty: Modern Warfare',120) ;
Insert into minute_streamed values ('2020-04-21 09:30:00', 'rick','Fornite',120) ;
Insert into minute_streamed values ('2020-04-20 10:31:00', 'jamie','Call of Duty: Modern Warfare',120) ;
Insert into minute_streamed values ('2020-04-21 09:30:00', 'jamie','Fornite',120) ;
Insert into minute_streamed values ('2020-04-18 12:00:00', 'alex','Fornite',125) ;
Insert into minute_streamed values ('2020-04-18 12:01:00', 'alex','Fornite',130) ;
Insert into minute_streamed values ('2020-06-18 14:00:00', 'alex','Fornite',120) ;
Alex has two entries in March. That means he streamed for 2 minutes. So, his hourly streamed for March will be 2/60.
I am trying to write a query: For each calendar month, output the list of streamers, who increased their hours streamed from the previous calendar month
For example, Alex has two entries for March, two entries for April, and one entry for June. So he streamed 2 minutes in March (because he has two entries), 2 minutes in April and 1 minute in June. I want to compare his last month, which is June and the previous calendar month. In this case, the previous calendar month is May, which Alex did not stream. So I need to say that he did not stream in May and he streamed in June. So, he increased his streaming compare to the previous calendar month
This my code below, but I want to compare the current streaming hour with the previous calendar month. Can you please help modify my query?
select
*
from(
select
*
,lag(total_monthly_hours,1) over(partition by username order by year,month) as prev_month
from(
select
username
,year(time_minute) as year
,month(time_minute) as month
,count(*)/60 as total_monthly_hours
from minute_streamed
group by year(time_minute), month(time_minute), username
order by month(time_minute) desc ) as temp ) as temp2
where total_monthly_hours > prev_month
If I understand correctly, you want to compare both the previous value and the previous time period. One way to do this is to calculate a "number of months" by multiplying the year by 12 and adding in the month number. Then you can see if the lag() is getting the value from the previous row:
select uym.*
from (select uym.*,
lag(total_monthly_hours) over (partition by username order by year, month) as prev_total_monthly_hours,
lag(month_cnt) over (partition by username order by year, month) as prev_month_cnt
from (select username,
year(time_minute) as year,
month(time_minute) as month,
year(time_minute) * 12 + month(time_minute) as month_cnt,
count(*)/60 as total_monthly_hours
from minute_streamed
group by year(time_minute), month(time_minute), username, month_cnt
) uym
) uym
where prev_month_cnt is null or
prev_month_cnt <> month_cnt - 1 or
(prev_month_cnt = month_cnt - 1 and prev_total_monthly_hours < total_monthly_hours);
Here is a db<>fiddle.

Limit some specific day in a week?

I have bunch of dates in my database, and now I want to use WHERE to limit a specific day in a week for eg. the date I have rn is 2019-01-01 etc. and I only want to see Monday, Tuesday and Wednesday among those date. How do I do that?
The code I showed below does not work just as a reference what I'm doing rn
CREATE VIEW weekend_reservation AS
SELECT CONCAT(last_name,',',first_name) AS "guest's name",
CONCAT(DATE_FORMAT(check_in_date,"%W,%M %d,%Y")) AS 'check_in_date',
CONCAT(DATE_FORMAT(check_out_date,"%W,%M %d,%Y")) AS 'check_out_date'
FROM guests JOIN reservations
USING(guest_id)
WHERE check_in_date BETWEEN 'Friday' AND 'Sunday'
ORDER BY check_in_date,check_out_date,last_name,first_name;
Well, I wouldn't do it just by changing the SELECT to have the day-of-the-week.
Instead:
CREATE VIEW weekend_reservation AS
SELECT CONCAT_WS(',', g.last_name, g.first_name) AS "guest's name",
DATE_FORMAT(r.check_in_date, '%W, %M %d,%Y')) AS check_in_date,
DATE_FORMAT(r.check_out_date, '%W,%M %d,%Y')) AS check_out_date
FROM guests g JOIN
reservations r
USING (guest_id)
WHERE DAYOFWEEK(r.check_in_date) IN (6, 7, 1)
ORDER BY check_in_date, check_out_date, last_name, first_name;
Notes:
CONCAT() after the DATE_FORMAT() does nothing.
The DAYOFWEEK() function returns days, with Sunday as 1 and Saturday as 7.
You should qualify all column names (i.e. use table alias), especially when a query has more than one table reference.
CONCAT_WS() is handy. It handles NULL values better than CONCAT().

Counting rows in event table, grouped by time range, a lot

Imagine I have a table like this:
CREATE TABLE `Alarms` (
`AlarmId` INT UNSIGNED NOT NULL AUTO_INCREMENT
COMMENT "32-bit ID",
`Ended` BOOLEAN NOT NULL DEFAULT FALSE
COMMENT "Whether the alarm has ended",
`StartedAt` TIMESTAMP NOT NULL DEFAULT 0
COMMENT "Time at which the alarm was raised",
`EndedAt` TIMESTAMP NULL
COMMENT "Time at which the alarm ended (NULL iff Ended=false)",
PRIMARY KEY (`AlarmId`),
KEY `Key4` (`StartedAt`),
KEY `Key5` (`Ended`, `EndedAt`)
) ENGINE=InnoDB;
Now, for a GUI, I want to produce:
a list of days during which at least one alarm were "active"
for each day, how many alarms started
for each day, how many alarms ended
The intent is to present users with a dropdown box from which they can choose a date to see any alarms active (started before or during, and ended during or after) on that day. So something like this:
+-----------------------------------+
| Choose day ▼ |
+-----------------------------------+
| 2017-12-03 (3 started) |
| 2017-12-04 (1 started, 2 ended) |
| 2017-12-05 (2 ended) |
| 2017-12-16 (1 started, 1 ended) |
| 2017-12-17 (1 started) |
| 2017-12-18 |
| 2017-12-19 |
| 2017-12-20 |
| 2017-12-21 (1 ended) |
+-----------------------------------+
I will probably force an age limit on alarms so that they are archived/removed after, say, a year. So that's the scale we're working with.
I expect anywhere from zero to tens of thousands of alarms per day.
My first thought was a reasonably simple:
(
SELECT
COUNT(`AlarmId`) AS `NumStarted`,
NULL AS `NumEnded`,
DATE(`StartedAt`) AS `Date`
FROM `Alarms`
GROUP BY `Date`
)
UNION
(
SELECT
NULL AS `NumStarted`,
COUNT(`AlarmId`) AS `NumEnded`,
DATE(`EndedAt`) AS `Date`
FROM `Alarms`
WHERE `Ended` = TRUE
GROUP BY `Date`
);
This uses both of my indexes, with join type ref and ref type const, which I'm happy with. I can iterate over the resultset, dumping the non-NULL values found into a C++ std::map<boost::gregorian::date, std::pair<size_t, size_t>> (then "filling the gaps" for days on which no alarms started or ended, but were active from previous days).
The spanner I'm throwing in the works is that the list should take into account location-based timezones, but only my application knows about timezones. For logistical reasons, the MySQL session is deliberately SET time_zone = '+00:00' so that timestamps are all kicked out in UTC. (Various other tools are then used to perform any necessary location-specific corrections for historical timezones, taking into account DST and whatnot.) For the rest of the application this is great, but for this particular query it breaks the date GROUPing.
Maybe I could pre-calculate (in my application) a list of time ranges, and generate a huge query of 2n UNIONed queries (where n = number of "days" to check) and get the NumStarted and NumEnded counts that way:
-- Example assuming desired timezone is -05:00
--
-- 3rd December
(
SELECT
COUNT(`AlarmId`) AS `NumStarted`,
NULL AS `NumEnded`,
'2017-12-03' AS `Date`
FROM `Alarms`
-- Alarm started during 3rd December UTC-5
WHERE `StartedAt` >= '2017-12-02 19:00:00'
AND `StartedAt` < '2017-12-03 19:00:00'
GROUP BY `Date`
)
UNION
(
SELECT
NULL AS `NumStarted`,
COUNT(`AlarmId`) AS `NumEnded`,
'2017-12-03' AS `Date`
FROM `Alarms`
-- Alarm ended during 3rd December UTC-5
WHERE `EndedAt` >= '2017-12-02 19:00:00'
AND `EndedAt` < '2017-12-03 19:00:00'
GROUP BY `Date`
)
UNION
-- 4th December
(
SELECT
COUNT(`AlarmId`) AS `NumStarted`,
NULL AS `NumEnded`,
'2017-12-04' AS `Date`
FROM `Alarms`
-- Alarm started during 4th December UTC-5
WHERE `StartedAt` >= '2017-12-03 19:00:00'
AND `StartedAt` < '2017-12-04 19:00:00'
GROUP BY `Date`
)
UNION
(
SELECT
NULL AS `NumStarted`,
COUNT(`AlarmId`) AS `NumEnded`,
'2017-12-04' AS `Date`
FROM `Alarms`
-- Alarm ended during 4th December UTC-5
WHERE `EndedAt` >= '2017-12-03 19:00:00'
AND `EndedAt` < '2017-12-04 19:00:00'
GROUP BY `Date`
)
UNION
-- 5th December
-- [..]
But, of course, even if I'm restricting the database to a year's worth of historical alarms, that's up to like 730 UNIONd SELECTs. My spidey senses tell me that this is a very bad idea.
How else can I generate these sort of time-grouped statistics? Or is this really silly and I should look at resolving the problems preventing me from using tzinfo with MySQL?
Must work on MySQL 5.1.73 (CentOS 6) and MariaDB 5.5.50 (CentOS 7).
The UNION approach is actually not far off a viable solution; you can achieve the same thing, without a catastrophically large query, by recruiting a temporary table:
CREATE TEMPORARY TABLE `_ranges` (
`Start` TIMESTAMP NOT NULL DEFAULT 0,
`End` TIMESTAMP NOT NULL DEFAULT 0,
PRIMARY KEY (`Start`, `End`)
);
INSERT INTO `_ranges` VALUES
-- 3rd December UTC-5
('2017-12-02 19:00:00', '2017-12-03 19:00:00'),
-- 4th December UTC-5
('2017-12-03 19:00:00', '2017-12-04 19:00:00'),
-- 5th December UTC-5
('2017-12-04 19:00:00', '2017-12-05 19:00:00'),
-- etc.
;
-- Now the queries needed are simple and also quick:
SELECT
`_ranges`.`Start`,
COUNT(`AlarmId`) AS `NumStarted`
FROM `_ranges` LEFT JOIN `Alarms`
ON `Alarms`.`StartedAt` >= `_ranges`.`Start`
ON `Alarms`.`StartedAt` < `_ranges`.`End`
GROUP BY `_ranges`.`Start`;
SELECT
`_ranges`.`Start`,
COUNT(`AlarmId`) AS `NumEnded`
FROM `_ranges` LEFT JOIN `Alarms`
ON `Alarms`.`EndedAt` >= `_ranges`.`Start`
ON `Alarms`.`EndedAt` < `_ranges`.`End`
GROUP BY `_ranges`.`Start`;
DROP TABLE `_ranges`;
(This approach was inspired by a DBA.SE post.)
Notice that there are two SELECTs — the original UNION is no longer possible, because temporary tables cannot be accessed twice in the same query. However, since we've already introduced additional statements anyway (the CREATE, INSERT and DROP), this seems to be a moot problem in the circumstances.
In both cases, each row represents one of our requested periods, and the first column equals the "start" part of the period (so that we can identify it in the resultset).
Be sure to use exception handling in your code as needed to ensure that _ranges is DROPped before your routine returns; although the temporary table is local to the MySQL session, if you're continuing to use that session afterwards then you probably want a clean state, particularly if this function is going to be used again.
If this is still too heavy, for example because you have many time periods and the CREATE TEMPORARY TABLE itself will therefore become too large, or because multiple statements doesn't fit in your calling code, or because your user doesn't have permission to create and drop temporary tables, you'll have to fall back on a simple GROUP BY over DAY(Date), and ensure that your users run mysql_tzinfo_to_sql whenever the system's tzdata is updated.

Mysql Select Only Staff with Specified Number of Consecutive Free Time Slots

Each staff already has a table of avail time slots in AvailSlots like this:
Staff_ID Avail_Slots_Datetime
1 2015-1-1 09:00:00
1 2015-1-1 10:00:00
1 2015-1-1 11:00:00
2 2015-1-1 09:00:00
2 2015-1-1 10:00:00
2 2015-1-1 11:00:00
3 2015-1-1 09:00:00
3 2015-1-1 12:00:00
3 2015-1-1 15:00:00
I need to find out which staff has, for example, 2 (or 3, 4, etc) CONSECUTIVE avail time slots at each time slot. As a novice, the INNER JOIN codes below is all I know to write if the query is for 2 consecutive time slots.
SELECT a.start_time, a.person
FROM a_free a, a_free b
WHERE (b.start_time = addtime( a.start_time, '01:00:00' )) and (a.person = b.person)
But, obviously, doing it that way, I would have to add more INNER JOIN codes - for each case - depending on whether the query is for 3, or 4, or 5 , etc consecutive available time slots at a given date/hour. Therefore, I want to learn a more efficient and flexible way to do the same. Specifically, the query code I need (in natural language) would be this:
For each time slot in AvailSlots, list one staff that has X (where X can
be any number I specify per query, from 1 to 24) consecutive datetime
slot starting from that datetime. In case more than one staff can meet
that criteria, the tie break is their "rank" which is kept in a
separate table below:
Ranking Table (lower number = higher rank)
Staff_ID Rank
1 3
2 1
3 2
If the answer is to use things like "mysql variables", "views", etc, please kindly explain how those things work. Again, as a total mysql novice, "select", "join", "where", "group by" are all I know so far. I am eager to learn more but have trouble understanding more advanced mysql concepts so far. Many thanks in advance.
Using a bit more data than you posted, I found a query that might do what you need. It does use the variables as you predicted :) but I hope it's pretty self-explanatory. Let's start with the table:
CREATE TABLE a_free
(`Staff_ID` int, `Avail_Slots_Datetime` datetime)
;
INSERT INTO a_free
(`Staff_ID`, `Avail_Slots_Datetime`)
VALUES
(1, '2015-01-01 09:00:00'),
(1, '2015-01-01 10:00:00'),
(1, '2015-01-01 11:00:00'),
(1, '2015-01-01 13:00:00'),
(2, '2015-01-01 09:00:00'),
(2, '2015-01-01 10:00:00'),
(2, '2015-01-01 11:00:00'),
(3, '2015-01-01 09:00:00'),
(3, '2015-01-01 12:00:00'),
(3, '2015-01-01 15:00:00'),
(3, '2015-01-01 16:00:00'),
(3, '2015-01-01 17:00:00'),
(3, '2015-01-01 18:00:00')
;
Then there's a query to find the consecutive slots. It lists start times of each pair, and marks each group of consecutive slots with a unique number. The case expression is where the magic happens, see the comments:
select
Staff_ID,
Avail_Slots_Datetime as slot_start,
case
when #slot_group is null then #slot_group:=0 -- initalize the variable
when #prev_end <> Avail_Slots_Datetime then #slot_group:=#slot_group+1 -- iterate if previous slot end does not match current one's start
else #slot_group -- otherwise just just keep the value
end as slot_group,
#prev_end:= Avail_Slots_Datetime + interval 1 hour as slot_end -- store the current slot end to compare with next row
from a_free
order by Staff_ID, Avail_Slots_Datetime asc;
Having the list with slot groups identified, we can wrap the query above in another one to get the lengths of each slot group. The results of the first query are treated as any other table:
select
Staff_ID,
slot_group,
min(slot_start) as group_start,
max(slot_end) as group_end,
count(*) as group_length
from (
select
Staff_ID,
Avail_Slots_Datetime as slot_start,
case
when #slot_group is null then #slot_group:=0
when #prev_end <> Avail_Slots_Datetime then #slot_group:=#slot_group+1
else #slot_group
end as slot_group,
#prev_end:= Avail_Slots_Datetime + interval 1 hour as slot_end
from a_free
order by Staff_ID, Avail_Slots_Datetime asc
) groups
group by Staff_ID, slot_group;
Note: if you use the same DB connection to execute the query again, the variables would not be reset, so the slot_groups numbering will continue to grow. This normally should not be a problem, but to be on the safe side, you need to execute something like this before or after:
select #prev_end:=null;
Play with the fiddle if you like: http://sqlfiddle.com/#!2/0446c8/15

MySQL Search Between Date and Time

I'm trying to setup an automatic event countdown. What I want to do is use MySQL to fill the countdown with the next upcoming event.
If the event is in the future, the code will show 'upcoming event - countdown' and if the event is currently taking place then show 'event happening'.
I have a table structure like this:
CREATE TABLE jos_eventlist_events (
id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
catsid INT UNSIGNED,
dates DATE,
times TIME,
enddates DATE,
endtimes TIME,
published TINYINT(1),
title VARCHAR(255)
) Engine=InnoDB;
INSERT INTO jos_eventlist_events
VALUES
(1, 6, '2012-01-15', '21:00', '2012-01-15', '22:00', 1, 'Partying'),
(2, 6, '2012-01-15', '23:00', '2012-01-16', '01:00', 1, 'More partying')
;
So essentially, the query should do something akin to this: If there are no events currently taking place, retrieve the next upcoming event. If there is an event taking place then display it.
The following query is a stepping stone as to what I'm trying to achieve.
SELECT catsid,id,dates,times,endtimes,published,title
FROM jos_eventlist_events
WHERE catsid = 6 AND published = 1
AND dates && times >= CURDATE() && CURTIME()
AND dates && endtimes <= CURDATE() && CURTIME()
LIMIT 1
Keep in mind that my server is 5 hours behind my local time.
I know I'm missing something really silly with this, but any help you can provide will be greatly appreciated.
try (I did not test it):
SELECT catsid,id,dates,times,endtimes,published,title
FROM jos_eventlist_events
WHERE catsid = 6 AND published = 1
AND (CONCAT(dates, ' ', times)>= NOW()
OR ( CONCAT(dates, ' ', times) < NOW()
AND CONCAT(enddates, ' ', endtimes) >= NOW() ) )
ORDER BY CONCAT(dates, ' ', times)
LIMIT 1