I´m doing SQL to display actual subject which is teaching currently by this and this teacher. It should displays only name of subject(f.e. it displays 'languages' at 8am at Teacher´s profile). In database I have table - timetable and there are data of start_time and end_time which are saved in DATETIME. I have problem how to interconnect SQL and PHP and then display.
I have this SQL query:
SELECT lessons.schoolday, lessons.start_time, lessons.end_time, lectors.lectorsurname, studentgroups.class_id, classes.grade, subjects.subjectname
FROM lessons INNER JOIN lectors ON lessons.lector_id=lectors.lector_id
INNER JOIN studentgroups ON lessons.studentgroup_id=studentgroups.studentgroup_id
INNER JOIN classes ON studentgroups.class_id=classes.class_id
INNER JOIN subjects ON lessons.subject_id=subjects.subject_id
WHERE lessons.start_time <= substring(('".date('Y-m-d H:i:s')."'),11,6)
AND lessons.end_time >= substring(('".date('Y-m-d H:i:s')."'),11,6)
AND lectors.lector_id=:id");
When I change date instead of interval(f.e. start_time->0000-00-00 08:00:00, end_time->0000-00-00 08:45:00), it is working. But in this way, it prints only Array(). HTML is displaying with Latte template and there is condition, if empty array, it displays message=Teacher is not teaching currently, but this is also not working.
.......
php code:
$stmt3 = $db->prepare(" SELECT l.schoolday, l.start_time, l.end_time, t.lectorsurname, sg.class_id, c.grade, s.subjectname
FROM lessons l
INNER JOIN lectors t ON l.lector_id=t.lector_id
INNER JOIN studentgroups sg ON l.studentgroup_id=sg.studentgroup_id
INNER JOIN classes c ON sg.class_id=c.class_id
INNER JOIN subjects s ON l.subject_id=s.subject_id
WHERE l.start_time <= CURTIME() AND l.end_time >= CURTIME() AND t.lector_id=:id
ORDER By c.grade, l.schoolday, l.start_time");
$stmt3->bindValue(":id", intval($_GET["id"]));
$stmt3->execute();
$data=$stmt3->fetchAll();
print_r($data);
$tplVars["lesson"] = $stmt3->fetchAll();
and latte template
<table>
.
.
.
<tr>
<th> Aktuálne vyučuje: </th>
</tr>
{foreach $lesson as $aktual}
{if !empty($aktual['grade'])}
<tr>
<td>{$aktual['grade']} </td>
</tr>
{/if}
{if ($aktual['grade']) == NULL}
<tr> <td> <span> Učiteľ momentálne nevyučuje </span></td></tr>
{/if}
{/foreach}
</table>
Search for some examples. with some aliases its better readable. Is a NOW() not enough? see this link for more MySql date and time functions
SELECT l.schoolday, l.start_time, l.end_time, t.lectorsurname, sg.class_id, c.grade, s.subjectname
FROM lessons l
INNER JOIN lectors t ON l.lector_id=t.lector_id
INNER JOIN studentgroups sg ON l.studentgroup_id=sg.studentgroup_id
INNER JOIN classes c ON sg.class_id=c.class_id
INNER JOIN subjects s ON l.subject_id=s.subject_id
WHERE l.start_time <= NOW() AND l.end_time >= NOW() AND t.lector_id=:id
Related
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;
I have no idea with joins and I am really having a trouble getting the logic. Can anyone please help me?
Here is my table Announcements:
AnnouncementID Subject Header Status
---------------------------------------------------
1 Peter Header 2 Publish
2 2x2 Header 3 Draft
3 Resignation Header 4 Publish
And here is another table ReadAnnouncements:
AnnouncementID Username Status
---------------------------------------------
1 User 1 Read
2 User 2 Read
2 User 3 Read
I want my result to be
AnnouncementID Username Status Header Subject
---------------------------------------------------------------
1 User 1 Read Peter Header 2
2 User 2 Read 2x2 Header 3
2 User 3 Read 2x2 Header 3
Please teach me how I am really confused been trying this for two days already.
<?php
$sql=" SELECT a.AnnouncementID,a.Created,r.Username,a.Status,a.Header,a.Body from Announcements a join ReadAnnouncements r using(AnnouncementID) WHERE a.Status = 'Publish'";
$result = mysqli_query( $conn,$sql);
while($rows = mysqli_fetch_array($result)){
$time = date('h:i:s a',strtotime($rows['Created']));
$date = date('Y-m-d',strtotime($rows['Created']));
if($rows['ReadStatus'] == 'Unread'){
echo '
<tr class="'.$rows['Status'].'clickable-row" >
<strong><td class="view-message dont-show"><div>'.$rows['Header'].'</div></td>
<td class="view-message "><a href="ViewAnnouncement.php?view_id='.$rows['AnnouncementID'].'" style="text-decoration: none" class="text-dark" ><div>'.substr($rows['Body'],0,90).'</div></a></td>
<!--<td class="view-message inbox-small-cells"><i class="fa fa-paperclip"></i></td>-->
<td class="view-message text-right"><div><h6>'.$time.''.'<br>'.''.$date.'</h6></div></td></strong></tr>
';
}else{
echo '<strong>
<tr class="'.$rows['Status'].'clickable-row" >
<strong><td class="view-message dont-show"><div>'.$rows['Header'].'</div></td>
<td class="view-message "><a href="ViewAnnouncement.php?view_id='.$rows['AnnouncementID'].'" style="text-decoration: none" class="text-dark" ><div>'.substr($rows['Body'],0,90).'</div></a></td>
<!--<td class="view-message inbox-small-cells"><i class="fa fa-paperclip"></i></td>-->
<td class="view-message text-right"><div><h6>'.$time.''.'<br>'.''.$date.'</h6></div></td></strong></tr>
</strong>';
}
}
?>
I want to select all rows from table announcements that are only Published and classify them if they are read or unread based on username and announcement id.
You can use the below query to get the result.
select a.AnnouncementID,r.Username,r.Status,a.Header,a.Subject
from Announcements a
join ReadAnnouncements r on r.AnnouncementID=a.AnnouncementID
Joins are pretty easy, check this explanation.
In your case, you can do something like this:
SELECT A.AnnouncementID, A.Username, R.Status, A.Header, A.Subject FROM Announcements A join ReadAnnouncements R USING(AnnouncementID)
You can use inner join. The INNER JOIN keyword selects records that have matching values in both tables.
SELECT a.AnnouncementID,r.Username,r.Status,a.Header,a.Subject
from Announcements a
join ReadAnnouncements r using(AnnouncementID)
Use JOIN clause to combine rows from two or more tables in a database, based on a related column between them ( in your case, AnnouncementID ).
When combine data from 2 tables, you have a few combinations possible:
(INNER) JOIN: Returns records that have matching values in both tables
LEFT (OUTER) JOIN: Return all records from the left table, and the matched records from the right table
RIGHT (OUTER) JOIN: Return all records from the right table, and the matched records from the left table
FULL (OUTER) JOIN: Return all records when there is a match in either left or right table
(source: https://www.w3schools.com/sql/sql_join.asp)
Using your database schema, you should use:
select * from Announcements as A INNER JOIN ReadAnnouncements as RA ON A.AnnouncementID RA.AnnouncementID
You don't mention which DBMS you are using, so SQL query above may differ.
I have two separate queries I am using to pull information for a report. A single year worked fine. However, if a month has more than 1 year it is not showing the correct responses.
Here are my two queries:
select SUM(rpt_complete.total) total, YEAR(bk_schedule.date) as year,zip_codes.zip_code
from rpt_complete
left join bk_schedule on rpt_complete.bk_id = bk_schedule.id
left join users_info on bk_schedule.users_info_id = users_info.id
left join zip_codes on users_info.zip_code = zip_codes.zip_code
group by zip_codes.zip_code, YEAR(bk_schedule.date)
select SUM(rpt_complete.total) total, MONTH(bk_schedule.date) as month, zip_codes.zip_code
from rpt_complete
left join bk_schedule on rpt_complete.bk_id = bk_schedule.id
left join users_info on bk_schedule.users_info_id = users_info.id
left join zip_codes on users_info.zip_code = zip_codes.zip_code
group by zip_codes.zip_code, MONTH(bk_schedule.date)
Then I loop through the results of month as such (and include year in the loop):
#foreach($month_total as $month)
<tr>
<td>{{ $month->zip_code }}</td>
<td>{{ $month->month }}</td>
<td>${{ $month->total }}</td>
<td>
#foreach($year_total as $year)
#if($month->zip_code == $year->zip_code)
{{ $year->year }}
#endif
#endforeach
</td>
<td>
#foreach($year_total as $year)
#if($month->zip_code == $year->zip_code)
${{ $year->total }}
#endif
#endforeach
</td>
</tr>
#endforeach
So if I have a total for December 2014 & December 2015 and my table is filtering on December 2014...December 2014 & 2015 will show in those results.
I guess I am having a hard time trying to figure out how to process the month and year to where it sums the data together.
EDIT: This is MySQL. Specifically I am using Laravel to output my SQL.
Here is my table: http://i.imgur.com/RClRDaW.png
as you can see 36066 has two entries due to being in two different months: However, they are also in 2 separate years. The year part is what is throwing my table off. You can see it's calculating it all together rather than just by month and totaling the year for that months entry.
My expected results are for 36066 1 month (January) to only show 2017 with that total and 36066 10 month (october) to only show the 2016 with that years total since those are the years that those two months belong to.
So, I need the results to look like this: http://i.imgur.com/jlFhR7x.png
I hope that provides so clarity.
add YEAR(bk_schedule.date) into the GROUP BY of your 2nd query
group by zip_codes.zip_code, MONTH(bk_schedule.date), YEAR(bk_schedule.date)
if you got error just include
YEAR(bk_schedule.date)
into your select fields
Try this:
SELECT
zip_codes.zip_code,
substr(bk_schedule.`date`, 1,7) AS ym,
SUM(rpt_complete.total) AS total
FROM ...
LEFT JOIN ...
GROUP BY 1,2
Updated:
If you want both year and year-month shown on same line, better use script to loop, OR use results from 2 SQLs and display togather. Otherwise try the following example (Which is not not encouraged):
SELECT y.geo, ym.ym, y.hit year_hit, ym.hit month_hit
FROM (
SELECT geo,year(ymd) y,sum(hit) hit FROM log_ip_hit
WHERE geo in ('US','CN')
AND ymd BETWEEN '2015-07-01' AND '2016-03-31'
GROUP BY 1,2
) AS y
JOIN (
SELECT geo,substr(ymd,1,7) ym,sum(hit) hit FROM log_ip_hit
WHERE geo in ('US','CN','AU')
AND ymd BETWEEN '2015-07-01' AND '2016-03-31'
GROUP BY 1,2
) AS ym ON y.geo = ym.geo AND y.y = substr(ym.ym,1,4)
After reading your updated question, I think the following is the best solution:
SELECT
zip_codes.zip_code,
year(bk_schedule.`date`) AS y,
substr(bk_schedule.`date`, 5,2) AS m,
SUM(rpt_complete.total) AS total
FROM ...
LEFT JOIN ...
GROUP BY 1,2,3
And when you display the result, use loop and sum based on year + zip.
I have a query that fetch the result from database as shown in this screenshot but I want the result like the second screenshot.
The query is:
SELECT ED.modelno,
ED.grade,
ED.type,
ED.class,
ED.thickness,
ED.over_size_type ,
ED.description,
ED.thread_pitch,
ED.thread_series,
ED.head_mark,
ED.qty_per_box,
ED.no_boxes,
ED.length,
ED.qty,
SQ.s_id,
SQ.supplier_code,
SQ.currancy,
SQ.moq,
SQ.weight_per1000,
SQ.us_dollor_per1000,
SQ.final_us_doller,
SQ.discount_ontotal,
SQ.us_dollor_kg,
SQ.ttl_us_dollor,
SQ.ttl_kg,
SQ.evaluation,
SQ.totadiscount_value,
SQ.pallet,
R.name AS nam,
R.companyname
FROM enquiry_details AS ED
LEFT OUTER JOIN supplier_quotation AS SQ ON ED.enq_detail_id=SQ.enq_detail_id
LEFT OUTER JOIN registration AS R ON SQ.s_id=R.id
WHERE ED.enq_id=15
GROUP BY R.name
Can you try this. change your group by to
Group by R.name, ED.modelno
With Rollup.
Thanks.
Here is my test result.
Hi here is the query.
I just assume that you need to total the totadiscount_value.
SELECT coalesce(ED.modelno,'Sub Total') modelno,
if (coalesce(ED.modelno,'Total')='Total',null,ED.grade) grade,
if (coalesce(ED.modelno,'Total')='Total',null,ED.type) type,
if (coalesce(ED.modelno,'Total')='Total',null,ED.class) class,
if (coalesce(ED.modelno,'Total')='Total',null,ED.thickness) thickness,
if (coalesce(ED.modelno,'Total')='Total',null,ED.over_size_type) over_size_type,
if (coalesce(ED.modelno,'Total')='Total',null,ED.description) description,
if (coalesce(ED.modelno,'Total')='Total',null,ED.thread_pitch) thread_pitch,
if (coalesce(ED.modelno,'Total')='Total',null,ED.thread_series) thread_series,
if (coalesce(ED.modelno,'Total')='Total',null,ED.head_mark) head_mark,
if (coalesce(ED.modelno,'Total')='Total',null,ED.qty_per_box) qty_per_box,
if (coalesce(ED.modelno,'Total')='Total',null,ED.no_boxes) no_boxes,
if (coalesce(ED.modelno,'Total')='Total',null,ED.length) length,
if (coalesce(ED.modelno,'Total')='Total',null,ED.qty) qty,
if (coalesce(ED.modelno,'Total')='Total',null,SQ.s_id) s_id,
if (coalesce(ED.modelno,'Total')='Total',null,SQ.supplier_code) supplier_code,
if (coalesce(ED.modelno,'Total')='Total',null,SQ.currancy) currancy,
if (coalesce(ED.modelno,'Total')='Total',null,SQ.moq) moq,
if (coalesce(ED.modelno,'Total')='Total',null,SQ.weight_per1000) weight_per1000,
if (coalesce(ED.modelno,'Total')='Total',null,SQ.us_dollor_per1000) us_dollor_per1000,
if (coalesce(ED.modelno,'Total')='Total',null,SQ.final_us_doller) final_us_doller,
if (coalesce(ED.modelno,'Total')='Total',null,SQ.discount_ontotal) discount_ontotal,
if (coalesce(ED.modelno,'Total')='Total',null,SQ.us_dollor_kg) us_dollor_kg,
if (coalesce(ED.modelno,'Total')='Total',null,SQ.ttl_us_dollor) ttl_us_dollor,
if (coalesce(ED.modelno,'Total')='Total',null,SQ.ttl_kg) ttl_kg,
if (coalesce(ED.modelno,'Total')='Total',null,SQ.evaluation) evaluation,
sum(SQ.totadiscount_value) totadiscount_value,
if (coalesce(ED.modelno,'Total')='Total',null,SQ.pallet) pallet,
coalesce(R.name,'Total') as nam,
if (coalesce(ED.modelno,'Total')='Total',null,R.companyname) companyname
FROM enquiry_details AS ED
LEFT OUTER JOIN supplier_quotation AS SQ ON ED.enq_detail_id=SQ.enq_detail_id
LEFT OUTER JOIN registration AS R ON SQ.s_id=R.id
WHERE ED.enq_id=15
group by R.name,ED.modelno
with rollup
Thanks.
I have two cycles in PHP, that I needed converting to smarty structure. Down includes PHP code.
Code:
<pre>
$query = mysqli_query($cnn, "SELECT *, COUNT(*) AS ph FROM course INNER JOIN completed_course ON course.id = completed_course.id_course GROUP BY course.id");
while ($row = mysqli_fetch_array($query)){
<tr> <td> <?php echo $row['id']; ?></td><td> <?php echo $row['nazev']; ? </td><td>
?php echo $row['ph']; ? </td> <td>
?php
$Number_of_graduates = mysqli_query($cnn, "SELECT COUNT(*) AS abs FROM participant where id_completed_course = $row[id]");
while ($rAbs = mysqli_fetch_array($Number_of_graduates)){
echo $rAbs['abs'];
} ?
</td>
</pre>
The question is. How to convert the second loop where first id from SQL?
Ok, so your question is really about SQL. Let's look at your queries. The first one looks like this:
SELECT *, COUNT(*) AS ph
FROM course
INNER JOIN completed_course ON course.id = completed_course.id_kurz
GROUP BY course.id
I'm assuming (because I don't know anything about your database scheme) that this is going to give a list of courses and the number of students (maybe - I don't know what's in the completed_course table) who completed them. As written, this query is going to also give you some data from the completed_course table, but it's likely to be meaningless since you're grouping only on course.id.
The second query is:
SELECT COUNT(*) AS abs
FROM participant
WHERE id_completed_course = {DATA FROM FIRST QUERY}
Presumably, this query is intended to give you the total number of participants of completed courses. To make that work, the WHERE clause could look like this:
SELECT COUNT(*) AS abs
FROM participant
WHERE id_completed_course IN (
SELECT course.id FROM
FROM course
INNER JOIN completed_course ON course.id = completed_course.id_kurz
)
Notice that I'm taking the values selected in the first query and making them part of an IN clause. This query can be simplified significantly - for instance, the JOIN in the subquery is really only selected ID values from the completed_course table:
SELECT COUNT(*) AS abs
FROM participant
WHERE id_completed_course IN (
SELECT id_kurz
FROM completed_course
)
And the query will actually be more efficient if you get rid of the subquery altogether and just join the participants to the completed_course table.
SELECT COUNT(*) AS abs
FROM participant
INNER JOIN completed_course ON participant.id_completed_course=completed_course.id_kurz
This last query is going to give you one value: the number of participants whose id_completed_course value corresponds to an item in the completed_course table. You can use the mysqli methods to retrieve this data and pass it to your Smarty template.