SQL- Query to select data using date selected using datepicker - php

I want to get data from database based on date selected using datepicker.
I am using the following query to get data between selected dated but what i need is like when i select from_date and to_date using datepicker and click a button i want all the data assocoated with the selected date to be displayed. What change should i make in the query (I think after Between). Someone please help me. Thanks in advance. I want to use this with PHP as a server page.
SELECT
EP.Employee_Id,
TD.Training_Id,
TD.Training_Date,
DT.Topic_Name,
EP.Employee_Name
FROM
`training_details` TD
INNER JOIN `domain_topics` DT ON DT.Domain_Id=TD.Domain_Id
INNER JOIN `trainer_details` TRD ON TRD.Training_Id = TD.Training_Id
INNER JOIN `employee_profile` EP ON TRD.Trainer_Id = EP.Employee_Id
WHERE
TD.Training_Date BETWEEN '2012-12-01' AND '2012-12-31';

This might help: If you are using POST method:
SELECT EP.Employee_Id, TD.Training_Id, TD.Training_Date, DT.Topic_Name, EP.Employee_Name
FROM `training_details` TD
INNER JOIN `domain_topics` DT ON DT.Domain_Id=TD.Domain_Id
INNER JOIN `trainer_details` TRD ON TRD.Training_Id = TD.Training_Id
INNER JOIN `employee_profile` EP ON TRD.Trainer_Id = EP.Employee_Id
WHERE TD.Training_Date >= '$_POST[from_date]' AND TD.Training_Date <= '$_POST[to_date]';
OR as in your query WHERE clause be like this:
WHERE TD.Training_Date BETWEEN $_POST[from_date] AND $_POST[to_date]
If you are using GET method, it will be:
WHERE TD.Training_Date BETWEEN $_GET[from_date] AND $_GET[to_date]

Related

Getting data from a table even if there's no data in table 2 that links to table 1

I'm creating a planner but the SQL statement I have now only shows employees that have something in table 2 (plannerEntries) and doesn't show the rest of the employees from table 1 (Employee_List).
I need all of the employees to be outputted into the table regardless of whether they have any jobs assigned for them for the week, so that they can have new jobs assigned easily.
This is my current SQL code
SELECT [EL].[Employee_Numer],
[PP].[workDate],
[PP].[jobNo],
[PP].[workDescription],
[PP].[timeOfDay],
[JF].[Description],
[EL].[Forename],
[EL].[Surname]
FROM plannerEntries AS PP
RIGHT JOIN [Employee_List] AS EL
ON [PP].[employeeNumber] = [EL].[Employee_Numer]
INNER JOIN [Job File] AS JF
ON [PP].[jobNo] = [JF].[Job No]
WHERE [PP].[workDate] >= '$monday'
AND [PP].[workDate] <= '$sunday'
ORDER BY [PP].[employeeNumber] ASC;
I expected all employees to be printed regardless of records in table 2, however only the employees with records in table 2 were printed. The below image is the actual output.
Please check the difference between inner join, left join, right join.
Something like this should do what you need:
SELECT
[EL].[Employee_Numer],
[PP].[workDate],
[PP].[jobNo],
[PP].[workDescription],
[PP].[timeOfDay],
[JF].[Description],
[EL].[Forename],
[EL].[Surname]
FROM
[Employee_List] AS EL
left join plannerEntries AS PP on [PP].[employeeNumber] = [EL].[Employee_Numer]
and [PP].[workDate] >= '$monday'
and [PP].[workDate] <= '$sunday'
left join [Job File] AS JF on [JF].[Job No] = [PP].[jobNo]
ORDER BY
[PP].[employeeNumber] ASC;

MySQL NOT IN function of array of data

This is my query. Using WHERE IN works normally in the MySQL GUI, however, when I run this query, it returns an empty result. I have checked them manually if the dates exist in the events table, and they really do.
SELECT * FROM venues v
LEFT JOIN reservations r ON v.venue_id = r.venue_id
LEFT JOIN events e ON e.reservation_id = r.reservation_id
WHERE e.date_of_use NOT IN ('$dates')
$dates is just a string of dates (i.e., 11-11-2018, 11-12-2018).
There is an error in the $dates string.
It should be formatted as '11-11-2018', '11-12-2018' i.e. each value should be enclosed in quotes to make IN query work.
Currently, your query looks like
WHERE e.date_of_use NOT IN ('11-11-2018, 11-12-2018');
which will search for rows with 2 dates instead of single dates.
Here's how a correct query would look like,
SELECT * FROM venues v
JOIN reservations r ON v.venue_id = r.venue_id
JOIN events e ON e.reservation_id = r.reservation_id
WHERE e.date_of_use NOT IN ('11-11-2018', '11-12-2018')
Update 1
Based on your comment, you have to implode the array with ','.
$dates = implode( "','", $date );
And then the below WHERE clause will work perfect,
WHERE e.date_of_use NOT IN ('$dates')
Update 2
If events and reservations tables are empty, then you need to use LEFT JOIN and fetch rows where date_of_use IS NULL
SELECT * FROM venues v
LEFT JOIN reservations r ON v.venue_id = r.venue_id
LEFT JOIN events e ON e.reservation_id = r.reservation_id
WHERE e.date_of_use NOT IN ('$dates')
OR e.date_of_use IS NULL
If $dates variable as you say, is a string with comma separated dates "11-11-2018, 11-12-2018" the query becomes:
WHERE e.date_of_use NOT IN ('11-11-2018, 11-12-2018')
whereas the right format would be:
WHERE e.date_of_use NOT IN ('2018-11-11', '2018-11-12')
i.e. each date should be intoduced separately inside IN and the date format is YYYY-MM-DD.
To handle also the case where events do not exists for a venue:
SELECT * FROM venues v
JOIN reservations r ON v.venue_id = r.venue_id
LEFT JOIN events e ON e.reservation_id = r.reservation_id
AND (e.date_of_use IS NULL OR e.date_of_use NOT IN ('2018-11-11', '2018-11-12'))
You can structure your array in php like this:
<?php
$DateArray=array();
$DateArray=["11-11-2018", "12-11-2018","11-11-2018", "11-12-2018"];
$Dates='(';
foreach ($DateArray as $key => $value)
{ $Dates=$Dates." ".$value.","; }
$Dates=rtrim($Dates,",");
$Dates=$Dates.")"; // contains ( 11-11-2018, 12-11-2018, 11-11-2018, 11-12-2018)
?>
And append the php variable like this:
SELECT * FROM venues v, reservations r, events e
WHERE v.venue_id = r.venue_id
AND e.reservation_id = r.reservation_id AND e.date_of_use NOT IN .$Dates;
Why don't use simplfy your query for debug?
Something like
SELECT * FROM events e
WHERE e.date_of_use NOT IN ('11-11-2018', '11-12-2018')
Replace dates array using implode function in PHP.
Also you would better use date type rather than text.
https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_date-format

SQL - select column inside different table if not null

I am trying to make a "recipe" system inside a game. The player can own a company and craft items in there.
I currently fetch the recipes per company type but I don't know how to write the query in a way that I can also fetch the item names and images if the item_id is not empty.
This is working:
SELECT a.recipe_id,
a.item1_id,
a.item1_uses,
a.item2_id,
a.item2_uses,
a.item3_id,
a.item3_uses,
a.item4_id,
a.item4_uses,
a.item5_id,
a.item5_uses,
a.newitem_id,
a.newitem_uses,
a.craft_description,
a.craft_button
FROM
company_recipes AS a,
company_types AS b
WHERE
a.type_id = b.type_id
AND
b.type_id = '".$type."';
"
A recipe can contain for example two items needed to craft something new, but it could also be 5. So if it's only 2, I only want to fetch the img, name of these 2 and the rest can be skipped.
I have a different table store_items that contains the img and name of the item. I was thinking something along the lines of an IF ELSE or CASE WHEN inside the query, but I'm not sure how I'd do that.
Something like: SELECT c.img, c.name FROM store_items AS c IF a.item1_id is not NULL.
I feel like I'm close to the solution, but missing the last step.
Thanks for the tips #jarlh, I've changed the code and came to this result. If you have any more tips to do it better I'm happy to listen. (I'm still a junior and thought myself by trial and error, so I might not have the best solutions at times... Which is why tips are highly appreciated).
SELECT cr.recipe_id,
cr.item1_id,
cr.item1_uses,
si1.name,
si1.img,
cr.item2_id,
cr.item2_uses,
si2.name,
si2.img,
cr.item3_id,
cr.item3_uses,
si3.name,
si3.img,
cr.item4_id,
cr.item4_uses,
si4.name,
si4.img,
cr.item5_id,
cr.item5_uses,
si5.name,
si5.img,
cr.newitem_id,
cr.newitem_uses,
si_new.name,
si_new.img,
cr.craft_description,
cr.craft_button
FROM
company_recipes AS cr
INNER JOIN company_types AS ct ON cr.type_id = ct.type_id
LEFT JOIN store_items AS si1 ON cr.item1_id = si1.item_id
LEFT JOIN store_items AS si2 ON cr.item2_id = si2.item_id
LEFT JOIN store_items AS si3 ON cr.item3_id = si3.item_id
LEFT JOIN store_items AS si4 ON cr.item4_id = si4.item_id
LEFT JOIN store_items AS si5 ON cr.item5_id = si5.item_id
LEFT JOIN store_items AS si_new ON cr.newitem_id = si_new.item_id
WHERE
ct.type_id = '".$type."';
I'm basically fetching everything now and handle the NULLs in the php code now.
Without seeing more info its had to see what you are trying achieve but you could start by using the the users inpute of the game to determine what data is first required before futher filtering. Try this:
Declare #Value int
set #Value = #User_input --- uses what ever the game user will
SELECT
a.recipe_id,
a.item1_id,
a.item1_uses,
a.item2_id,
a.item2_uses,
a.item3_id,
a.item3_uses,
a.item4_id,
a.item4_uses,
a.item5_id,
a.item5_uses,
a.newitem_id,
a.newitem_uses,
a.craft_description,
a.craft_button
--- you can insert more columns but i stopped here as i dont know what data you have in the other tables.
FROM
company_recipes a
INNER JOIN company_types b ON a.type_id = b.type_id
INNER JOIN store_items c ON c.type_id = b.type_id
WHERE
b.type_id = #Value; --- '".$type."';

Converting oracle to mysql to select listagg and left join

Please, I have the below oracle query to select post and list all share image attached to a post and at the same time join user table and post table. My problem now is to run this query in MySQL. I have tried so many modifications but it kept giving me errors can someone help out?
SELECT
post_image_id,
LISTAGG(photo_url, ", ") WITHIN GROUP (ORDER BY photo_url) imgs
FROM social_post_photos
GROUP BY post_image_id;
WITH i AS (
SELECT post_image_id,
LISTAGG(photo_url, ", ") WITHIN GROUP (ORDER BY photo_url) imgs
FROM social_post_photos
GROUP BY post_image_id
)
SELECT sp.post_body_message, i.imgs AS images
FROM social_posts sp
LEFT JOIN vendor_account va
ON sp.vendor_owner_id = va.eu_vendor_id
LEFT JOIN i
ON sp.social_page_id = i.post_image_id
WHERE sp.social_page_id = 'page1'
AND sp.vendor_owner_id = 'v100'
FULL DEMO WITH TABLE http://sqlfiddle.com/#!9/9c39ef/2
The mysql equivalent of listagg is group_concat -
SELECT
post_image_id,
group_concat(photo_url ORDER BY photo_url) imgs
FROM social_post_photos
GROUP BY post_image_id;
There is no with(cte) in mysql until version 8 but i think you can replace this in your query with a sub query to create i.

Select child records from tables mysql

I got the bellow piece of select statement that got level 2 child records, having problems to got deeper, can anyone help out?
SELECT
id_mobile AS ID_PROJETO,
UM.qtd_UC,
AM.qtd_AMBIENTE
FROM projetos_mobile AS PM
LEFT JOIN (
SELECT
COUNT(id) AS qtd_UC,
projeto,
data_hora_importacao,
id_uc_mobile
FROM ucs_mobile
WHERE data_hora_importacao = '2015-05-15 17:21:02'
GROUP BY projeto) AS UM
ON PM.id_mobile = UM.projeto
LEFT JOIN (
SELECT
COUNT(id_uc_mobile) AS qtd_AMBIENTE,
id_uc_mobile
FROM ucs_mobile
LEFT JOIN (
SELECT
uc
FROM ambientes_mobile AS s
WHERE data_hora_importacao = '2015-05-15 17:21:02') AS G
ON G.uc = ucs_mobile.id_uc_mobile
WHERE data_hora_importacao = '2015-05-15 17:21:02') AS AM
ON UM.id_uc_mobile = AM.id_uc_mobile
WHERE PM.data_hora_importacao = '2015-05-15 17:21:02'
http://sqlfiddle.com/#!9/2eecf
here is a sqlfiddle if anyone want to try a solution. I have the specific hierarchy: projeto>uc>ambiente>secao>medicoes
ucs_mobile.projeto refers to projetos_mobile.id_mobile
ambientes_mobile.uc refers to ucs_mobile.id_uc_mobile
secoes_iluminacao_mobile.ambiente refers to ambientes_mobile.id_ambiente_mobile
I need a count of each child for the parent I pass, I will have 5 functions that
return the count of each child for a given parent, for example, for a projeto parent I should have count(ucs),count(ambientes),count(secoes),count(medicoes)
So, hope you guys can help me. The database is terrible ugly but that's is what I got. Appreciate any help.
When you have really large queries like this, it can often be helpful to break them down individually, starting from the ground up and patching them together.
I started by just getting the count of each ucs_mobile row for each projetos_mobile value. You can do that by joining the two tables on the related row, and using COUNT(DISTINCT um.id) to get the number of rows. There are other ways to do it, but this particular method will scale better for the rest of your query:
SELECT pm.id, COALESCE(COUNT(DISTINCT um.id), 0) AS qty_uc
FROM projetos_mobile pm
LEFT JOIN ucs_mobile um ON um.data_hora_importacao = '2015-05-15 17:21:02' AND um.projeto = pm.id_mobile
GROUP BY pm.id;
The COALESCE function will be used to fill 0 counts. As long as you remember to use the DISTINCT keyword, and group by the proper id, you can just add in the child rows like so:
SELECT
pm.id,
COALESCE(COUNT(DISTINCT um.id), 0) AS qty_uc,
COALESCE(COUNT(DISTINCT am.id), 0) AS qty_am,
COALESCE(COUNT(DISTINCT sim.id), 0) AS qty_sim
FROM projetos_mobile pm
LEFT JOIN ucs_mobile um ON um.data_hora_importacao = '2015-05-15 17:21:02' AND um.projeto = pm.id_mobile
LEFT JOIN ambientes_mobile am ON am.data_hora_importacao = um.data_hora_importacao AND am.uc = um.id_uc_mobile
LEFT JOIN secoes_iluminacao_mobile sim ON sim.data_hora_importacao = am.data_hora_importacao AND sim.ambiente = am.id_ambiente_mobile
GROUP BY pm.id;
Here is an SQL Fiddle example. NOTE I changed your sample data slightly to ensure my query was working as expected.
Also, a side note. I noticed as you went along that you kept using the same date in your WHERE clauses, so I just joined each table on the date as well, and made sure that in my very first join I looked for the date specified, which in turn will carry its way over to the other tables.

Categories