mysql select equal data with same date wise - php

I'm trying to run a mysql join query fetching data from 3 tables.
Table 1: user
Table 2: Outtiming
Table 3: Intiming
I want to show same date data from outtiming and intiming tables with same dates.
e.g: 2017-09-13 = 2017-09-13
But I'm not getting data with same dates.
$query = "SELECT ur.username, ur.user_department, it.*, ot.*
FROM users ur
INNER JOIN intiming it ON ur.staff_id=it.staff_id
INNER JOIN outtiming ot ON ur.staff_id=ot.staff_id
WHERE it.staff_id=".$employee."
AND it.date >= '$startDate' AND ot.date <= '$endDate'";
Result
mysql query result

Add an addition condition in your WHERE statement to check matching dates: it.date = ot.date . Full query:
$query = "SELECT ur.username, ur.user_department, it.*, ot.*
FROM users ur
INNER JOIN intiming it ON ur.staff_id=it.staff_id
INNER JOIN outtiming ot ON ur.staff_id=ot.staff_id
WHERE it.staff_id=".$employee."
AND it.date >= '$startDate' AND ot.date <= '$endDate'
AND it.date = ot.date ";

Related

Solution for "Subquery returns more than 1 row"

I'm trying to substitute my join SQL code to a different code without any of JOIN statements for faster data retrieval. However, i'm getting the error below.
#1242 - Subquery returns more than 1 row
What i would like to do, get all rows from one table 'tbl_my_itemlist' and JOIN to other more tables, tbl_register and tbl_register without using JOIN statements.
The Code using JOIN statement (works fine).
SELECT
tbl_screenshots.screenshot_image_url,
mit.my_itemlist_id,
mit.item_name,
mit.item_initial_cost,
mit.item_offer_cost,
mit.offer_date_from,
mit.offer_date_to
FROM
(
SELECT
my_itemlist_id
FROM
tbl_my_itemlist
WHERE
offer_date_from >='2020-10-20' AND offer_date_to <= '2020-10-30' AND
item_deleted_status = 'active'
) mlist
JOIN tbl_my_itemlist mit ON
mit.my_itemlist_id = mlist.my_itemlist_id
RIGHT JOIN tbl_screenshots ON mit.my_itemlist_id =
tbl_screenshots.my_itemlist_id
RIGHT JOIN tbl_register ON tbl_register.register_id = mit.register_id
GROUP BY
mit.my_itemlist_id
ORDER BY mit.offer_date_to ASC LIMIT 2
The code i'm substituting the JOIN statement code with.
SELECT
mit.my_itemlist_id,
mit.item_name,
mit.item_initial_cost,
mit.item_offer_cost,
mit.offer_date_from,
mit.offer_date_to,
(
SELECT
reg.business_name
FROM
tbl_register reg
WHERE
reg.register_id = mit.register_id
) reg_sql,
(
SELECT
sshots.screenshot_image_url
FROM
tbl_screenshots sshots
WHERE
sshots.my_itemlist_id = mit.my_itemlist_id
) sshots_sq
FROM
tbl_my_itemlist mit
WHERE
mit.offer_date_from >= '2020-10-20' AND mit.offer_date_to <= '2020-10-30' AND mit.item_deleted_status = 'active'
GROUP BY
mit.my_itemlist_id
ORDER BY
mit.offer_date_to ASC
LIMIT 2
I'm trying to build an SQL query that can retrieve data from million records within very short period of time as compared to using the JOIN statement.

Join2 tables and group by date

I want to sum all win_ticket and divide it to the sum of all sold_ticket from 2 tables to get the percentage and then group it by date.
This is not working at all.....
sold_ticket
customer_winner
$query = "SELECT
sold_ticket.date, sold_ticket.sold_ticket,
SUM(sold_ticket) AS sold_ticket,
customer_winner.date, customer_winner.win_ticket,
SUM(win_ticket) AS lottery_win
FROM sold_ticket
INNER JOIN customer_winner
ON sold_ticket.date = customer_winner.date
GROUP BY date
";
need to grouping sold_ticket.date or customer_winner.date or both of them.
try this
SELECT sold_ticket.date,
SUM (sold_ticket) AS sold_ticket,
SUM(customer_winner.win_ticket),
SUM (win_ticket) AS lottery_win
FROM sold_ticket
INNER JOIN customer_winner ON sold_ticket.date= customer_winner.date
GROUP BY sold_ticket.date;

Optimizing the SQL Query to get data from large amount MySQL database

I am having a problem getting data from a large amount MySQL database.
With the below code it is ok to get the list of 10K patients and 5K appointments which is our test server.
However, on our live server, the number of patients is over 100K and the number of appointments is over 300K and when I run the code after a while it gives 500 error.
I need the list of the patients whose patient_treatment_status is 1 or 3 and has no appointment after one month from their last appointment. (The below code is working for small amount of patients and appointments)
How can I optimise the first database query so there will be no need the second database query in the foreach loop?
<?php
ini_set('memory_limit', '-1');
ini_set('max_execution_time', 0);
require_once('Db.class.php');
$patients = $db->query("
SELECT
p.id, p.first_name, p.last_name, p.phone, p.mobile,
LatestApp.lastAppDate
FROM
patients p
LEFT JOIN (SELECT patient_id, MAX(start_date) AS lastAppDate FROM appointments WHERE appointment_status = 4) LatestApp ON p.id = LatestApp.patient_id
WHERE
p.patient_treatment_status = 1 OR p.patient_treatment_status = 3
ORDER BY
p.id
");
foreach ($patients as $row) {
$one_month_after_the_last_appointment = date('Y-m-d', strtotime($row['lastAppDate'] . " +1 month"));
$appointment_check = $db->single("SELECT COUNT(id) FROM appointments WHERE patient_id = :pid AND appointment_status = :a0 AND (start_date >= :a1 AND start_date <= :a2)", array("pid"=>"{$row['id']}","a0"=>"1","a1"=>"{$row['lastAppDate']}","a2"=>"$one_month_after_the_last_appointment"));
if($appointment_check == 0){
echo $patient_id = $row['id'].' - '.$row['lastAppDate'].' - '.$one_month_after_the_last_appointment. '<br>';
}
}
?>
First off, this subquery likely does not do what you think it does.
SELECT patient_id, MAX(start_date) AS lastAppDate
FROM appointments WHERE appointment_status = 4
Without a GROUP BY clause, that subquery will simply take the maximum start_date of all appointments with appointment_status=4, and then arbitrarily pick one patient_id. To get the results you want you'll need to GROUP BY patient_id.
For your overall question, try the following query:
SELECT
p.id, p.first_name, p.last_name, p.phone, p.mobile,
LatestApp.lastAppDate
FROM
patients p
INNER JOIN (
SELECT patient_id,
MAX(start_date) AS lastAppDate
FROM appointments
WHERE appointment_status = 4
GROUP BY patient_id
) LatestApp ON p.id = LatestApp.patient_id
WHERE
(p.patient_treatment_status = 1
OR p.patient_treatment_status = 3)
AND NOT EXISTS (
SELECT 1
FROM appointments a
WHERE a.patient_id = p.patient_id
AND a.appointment_status = 1
AND a.start_date >= LatestApp.lastAppDate
AND a.start_date < DATE_ADD(LatestApp.lastAppDate,INTERVAL 1 MONTH)
)
ORDER BY
p.id
Add the following index, if it doesn't already exist:
ALTER TABLE appointments
ADD INDEX (`patient_id`, `appointment_status`, `start_date`)
Report how this performs and if the data appears correct. Provide SHOW CREATE TABLE patient and SHOW CREATE TABLE appointments for further assistance related to performance.
Also, try the query above without the AND NOT EXISTS clause, together with the second query you use. It is possible that running 2 queries may be faster than trying to run them together, in this situation.
Note that I used an INNER JOIN to find the latest appointment. This will result in all patients that have never had an appointment to not be included in the query. If you need those added, just UNION the results those found by selecting from patients that have never had an appointment.

Multiple PHP subqueries not giving desired result

I have a MySQL table from which I want to extract attendance information(Student Id, course/subject for attendance, date range,whether the student was present or not). I have written the following query:
SELECT
COUNT(a_id),
(
SELECT COUNT(*) FROM attendance
WHERE state = 'present'
AND `dater` BETWEEN '$a' AND '$b'
) AS Count,
stud_id
FROM attendance
WHERE
stud_id =(SELECT id FROM users WHERE NAME = '$stud')
Which is giving me the correct results, but when I change the student,its not giving me the correct count for the days recorded for present. Not mention that I have not yet added the course parameter into the query
The MySQL table is as follows:
I need help for the query to return the desired results(Count the accurate days present for each student, as well as adding the course parameter into the query so that the query will look for attendance records for a specific course, for a specific student, for a specified date range).
Looks like you want to seperate your queries:
Select (select count(*) from <database>.attendance where state = 'present' AND (dater between '$a' and '$b') AND name=(SELECT id FROM users WHERE NAME = '$stud')) as present, (select count(*) from <database>.attendance where state = 'absent' AND (dater between '$a' and '$b') AND name=(SELECT id FROM users WHERE NAME = '$stud')) as absent from <database>.attendance WHERE stud_id =(SELECT id FROM users WHERE NAME = '$stud');
try this :)
Resolved it using JOIN as follows:
SELECT u.id, a.stud_id, a.course_id, count(*) FROM attendance a
JOIN users u ON u.id=a.stud_id
JOIN courses c ON c.c_id=a.course_id
WHERE a.state='present' and dater between '2017-09-01' and '2017-09-14'
GROUP BY a.stud_id, a.course_id;
Thanks for your help.

Searching between two dates in mysql

I have two tables and this table name is "rooms" and other one is "bookings"
I joined two tables now, I want values when i will search between book_form = "2016-12-30" and book_to = "2016-12-31" it will be return true because this two dates does not exists in the "bookings" table, and when search between book_form = "2016-12-30" and book_to = "2017-01-05" or book_form = "2017-01-03" and book_to = "2017-01-15" it will be return false because this date exists in bookings table.
This is my query.
select * from rooms join room_book on rooms.room_id = room_book.room_id where status = 'available' and room_book.book_from NOT BETWEEN '2016-12-30' AND room_book.book_to NOT BETWEEN '2016-12-31'
NOTE: Sorry actually the column book_from date is 2017-01-01 in the bookings table.
select *
from rooms
join room_book on rooms.room_id = room_book.room_id
where status = 'available'
and room_book.book_from >= '2016-12-30'
AND room_book.book_to <= '2016-12-31'
Try like this.
A simple SQL query should return only those rooms without a booking that includes the supplied date:
SELECT *
FROM rooms
LEFT JOIN room_book
ON room_book.room_id = rooms.room_id
AND 'search_date' BETWEEN room_book.book_from AND room_book.book_to
WHERE rooms.room_id IS NULL
AND rooms.status = 'available'
Substitute the date you are searching for search_date above.
By using a LEFT JOIN, you will get all of the records in rooms. The IS NULL test in the where clause eliminates those rows that don't have a matching row in room_book.

Categories