I have a query that display all my CLASS details, now I want a sub query that will count all enrolled student in that class.
I tried using two separate query and trying to merge them but I'm not successful doing so.
This is my query so far:
$str = "SELECT
class.id,
class.code AS classcode,
section.name AS sectionname,
subject.code,
class.units,
sched.name AS schedule,
class.slots,
class.dissolved,
(SELECT
Count(enrolldet.enrollno)
FROM
enrolldet
Inner Join enroll ON enrolldet.enrollno = enroll.enrollno
Inner Join class ON enrolldet.class = class.id
WHERE
enroll.validated = '1' AND
class.id = class.id) AS enrolled
FROM
class
Left Join sched ON class.sched = sched.id
Left Join section ON class.section = section.id
Left Join subject ON class.subject = subject.id
";
You don't need all those joins in the subquery. This should suffice:
(SELECT Count(*)
FROM enrolldet ed JOIN
enroll e
ON ed.enrollno = e.enrollno
WHERE e.validated = 1 AND
ed.class = c.id
) AS enrolled
That is, you don't need class in the subquery. And, I'm guessing that validated is a number so I removed the single quotes around "1".
You can't have the class table of both the main query and the subquery named class, because the subquery has access to both tables and this results in the SQL engine being confused due to the ambiguity.
To fix your query, give an alias, like cls, the inner one and change the AND clause to:
AND `class`.`id` = `cls`.`id`
Also, note that your subquery can be simplified by removing the inner class table altogether, since the subquery can access the class table of the main query, as already mentioned.
Code:
SELECT
`class`.`id`,
`class`.`code` AS `classcode`,
`section`.`name` AS `sectionname`,
`subject`.`code`,
`class`.`units`,
`sched`.`name` AS `schedule`,
`class`.`slots`,
`class`.`dissolved`,
(
SELECT COUNT(`enrollno`)
FROM `enrolldet`
INNER JOIN `enroll`
ON `enrolldet`.`enrollno` = `enroll`.`enrollno`
WHERE `enroll`.`validated` = '1'
AND `enrolldet`.`class` = `class`.`id`
) AS `enrolled`
FROM `class`
LEFT JOIN `sched` ON `class`.`sched` = `sched`.`id`
LEFT JOIN `section` ON `class`.`section` = `section`.`id`
LEFT JOIN `subject` ON `class`.`subject` = `subject`.`id`
$str = "SELECT
c.id,
c.code AS classcode,
section.name AS sectionname,
subject.code,
c.units,
sched.name AS schedule,
c.slots,
c.dissolved,
(SELECT
Count(e.enrollno)
FROM
enrolldet AS e
Inner Join enroll ON e.enrollno = enroll.enrollno
Inner Join class ON e.class = class.id
WHERE
enroll.validated = '1' AND
class.id = c.id) as enrolled
FROM
class AS c
Left Join sched ON c.sched = sched.id
Left Join section ON c.section = section.id
Left Join subject ON c.subject = subject.id";
i got the correct answer using this. for future reference. i just added aliases for each table
Related
I'm very new to PHP and SQL. I'm trying to display search results from my MySQL database via a search box and the SELECT statement I'm using to clarify what results should be displayed will only accept two OR conidtions, and after that won't let me add any more. It just turns gray in Atom and doesn't do anything when I try to search by that condition in the interface. Here is what it looks like in Atom, and the code: SELECT statement
$sql = "SELECT * FROM Clients AS c
INNER JOIN Rentals AS r ON c.Client_ID = r.Client_ID
INNER JOIN Cases AS ca ON r.Client_ID = ca.Case_ID
INNER JOIN Judgments AS j ON ca.Case_ID = j.Case_ID
INNER JOIN Lockouts AS l ON j.Judgment_ID = l.Judgment_ID
WHERE First_name = '$search' OR Last_name = '$search'
OR Phone_number = '$search' OR Email_address = '$search';";
I'm wondering how I can add more OR conditions to the SELECT statement, or if there's some other way I should be approaching this. Thank you!
$sql = "SELECT * FROM Clients AS c
INNER JOIN Rentals AS r ON c.Client_ID = r.Client_ID
INNER JOIN Cases AS ca ON r.Client_ID = ca.Case_ID
INNER JOIN Judgments AS j ON ca.Case_ID = j.Case_ID
INNER JOIN Lockouts AS l ON j.Judgment_ID = l.Judgment_ID
WHERE c.First_name = '$search' OR c.Last_name = '$search'
OR c.Phone_number = '$search' OR c.Email_address = '$search';";
I am assuming that First_name, Last_name etc column is in Clients table that is why i have used c.First_name and so on. As you have aliased Clients table as c.
Note INNER JOIN clause join table if when ON condition meet and get result.
You can use LEFT JOIN clause to get LEFT TABLE (Clients ) event if Join condition not meet.
I can't get a left join to work in my prepared statement.
"SELECT DISTINCT(a.auto_id), m.merk, a.model, a.uitvoering, a.standaardtekst, a.prijs, a.prijs2, a.prijs3, a.handelsprijs, a.aanmaak, s.soort, z.prijs_id
/*,GROUP_CONCAT(DISTINCT(apc.NL) ORDER BY apc.NL ASC)*/
FROM autocom_new.auto_new a
INNER JOIN autocom_new.tbl_merken m
ON a.merk = m.merk_id
INNER JOIN autocom_new.tbl_soort s
ON a.soort = s.soort_id
INNER JOIN autocom_new.auto_zoekmachines z
ON a.auto_id = z.auto_id
/*
LEFT JOIN autocom_new.auto_accessoire acc
ON a.auto_id = acc.auto_id
LEFT JOIN autocom_new.tbl_autopricecode_new apc
ON acc.code_id = apc.code_id
*/
WHERE a.ac LIKE ? AND a.flag = ?"
The commented parts are the parts that aren't working.
I have no idea what I'm doing wrong.
EDIT
First of all I forgot that both tables have a column ac, so I've changed the where statement a bit. The left joins are working now, but the part in the select is still not working
So the problem was that I forgot a GROUP BY.
"SELECT DISTINCT(a.auto_id), m.merk, a.model, a.uitvoering, a.standaardtekst, a.prijs, a.prijs2, a.prijs3, a.handelsprijs, a.aanmaak, s.soort, z.prijs_id,
GROUP_CONCAT(DISTINCT(apc.NL) ORDER BY apc.NL ASC)
FROM autocom_new.auto_new a
INNER JOIN autocom_new.tbl_merken m
ON a.merk = m.merk_id
INNER JOIN autocom_new.tbl_soort s
ON a.soort = s.soort_id
INNER JOIN autocom_new.auto_zoekmachines z
ON a.auto_id = z.auto_id
LEFT JOIN autocom_new.auto_accessoire acc
ON a.auto_id = acc.auto_id
LEFT JOIN autocom_new.tbl_autopricecode_new apc
ON acc.code_id = apc.code_id
WHERE a.ac LIKE ? AND a.flag = ?
GROUP BY a.auto_id"
I have a complex query consisting of lots of Inner and Left Joins and i am attempting to get the number of record back in a certain table using the COUNT Function of SQL.
I am attempting to get the number of records in the 'held_proposals' table for each proposal using the proposal_id since I'll be outputting the data into a table using a foreach loop.
In essence I would like to show how many students have 'held' a proposal against each proposal.
This was my attempt:
SELECT p.proposal_id, p.proposal_title, p.description, u.user_record_id, u.forename, u.surname, c.course_title, h.*,
GROUP_CONCAT(DISTINCT t.tag_title) AS tags FROM proposal p
LEFT JOIN user u on u.user_record_id = p.user_record_id
LEFT JOIN course_details c on c.course_code = p.course_code
LEFT JOIN record r on r.proposal_id = p.proposal_id
LEFT JOIN proposal_tags pt on pt.proposal_id = p.proposal_id
LEFT JOIN tag_details t on t.tag_code = pt.tag_code
LEFT JOIN (
SELECT h.student_record_id, COUNT(*) AS Held
FROM held_proposals h
) H on h.proposal_id = p.proposal_id
WHERE p.source = "Supervisor"
AND (r.status_code not in (3,8) OR r.status_code IS NULL)
GROUP BY p.proposal_id;
the table currently looks like this:
I would like to add the value returned from the 'held_proposals' table for each proposal at the end of the table as another column.
Could any please provide me with some guidance as to how I can achieve this in the SQL query. Thank you in advance.
You need to group the count inside the query which you are joining something as
SELECT
p.proposal_id,
p.proposal_title,
p.description,
u.user_record_id,
u.forename,
u.surname,
c.course_title, coalesce(h.Held,0) as `Held`,
GROUP_CONCAT(DISTINCT t.tag_title) AS tags
FROM proposal p
LEFT JOIN user u on u.user_record_id = p.user_record_id
LEFT JOIN course_details c on c.course_code = p.course_code
LEFT JOIN record r on r.proposal_id = p.proposal_id
LEFT JOIN proposal_tags pt on pt.proposal_id = p.proposal_id
LEFT JOIN tag_details t on t.tag_code = pt.tag_code
LEFT JOIN (
SELECT proposal_id, COUNT(*) AS Held
FROM held_proposals group by proposal_id
) h on h.proposal_id = p.proposal_id
WHERE p.source = "Supervisor"
AND (r.status_code not in (3,8) OR r.status_code IS NULL)
GROUP BY p.proposal_id;
I currently have a database with 12 tables. I am doing a php query to pull the information from the database but I am not getting anything displayed. The query alone bridges all the tables starting with table schedule that have a foreign key related. Should I need to start the query from the table class and bridge with other tables?
TABLE DESIGN- PICTURE
If you like to duplicate my design- QUERY
$query = ("SELECT class_name, class_caption, class_credit_hours, class_description
FROM schedule
INNER JOIN section
ON class.id = section.class_id
INNER JOIN faculty
ON faculty.id = section.faculty_id
INNER JOIN faculty
ON faculty.id = office_hours.faculty_id
INNER JOIN faculty_titles
ON faculty_titles.faculty_id = faculty.id
INNER JOIN faculty_education
ON faculty_education.faculty_id = faculty.id
INNER JOIN section
ON section.faculty_id = faculty.id
INNER JOIN class
ON class.id = section.class_id
INNER JOIN major_class_br
ON major_class_br.class_id = class.id
INNER JOIN major_minor
ON major_class_br.major_minor_id = major_minor.id
");
//execute query
$result = mysql_query($query);
if ($result){
$totalhours = 0;
while ($row = mysql_fetch_assoc( $result ))
{
print "<b>" . $row['class_name'] . "</b><br>";
print $row['class_caption'] . "<br>";
print $row['class_description'] . "<br>";
print $row ['class_credit_hours'] . "hrs. <br>";
print "------------------------------<br />";
$totalhours += $row['class_credit_hours'];
}
}
SQL fiddle query
SELECT class_name, class_caption, class_credit_hours, class_description
FROM schedule
INNER JOIN section
ON class.id = section.class_id
Right here there's a problem: you are doing a INNER JOIN using the field 'class.id' but the table 'class' isn't in either side of the JOIN. So it won't work.
The query should start like this:
SELECT class_name, class_caption, class_credit_hours, class_description
FROM class
INNER JOIN section
ON class.id = section.class_id
And then do the JOIN with the table 'schedule' with the table it shares a common index (I guess it would be class).
The complete query should be something like this:
SELECT class.class_name, class.class_caption, class.class_credit_hours, class.class_description
FROM class
INNER JOIN section
ON class.id = section.class_id
INNER JOIN faculty
ON faculty.id = section.faculty_id OR faculty.id = office_hours.faculty_id
INNER JOIN faculty_titles
ON faculty_titles.faculty_id = faculty.id
INNER JOIN faculty_education
ON faculty_education.faculty_id = faculty.id
INNER JOIN major_class_br
ON major_class_br.class_id = class.id
INNER JOIN major_minor
ON major_class_br.major_minor_id = major_minor.id
INNER JOIN sched_sect_br
ON sched_sect_br.section_id = section.id
INNER JOIN schedule
ON schedule.id = sched_sect_br.schedule_id
INNER JOIN semester
ON semester.id = schedule.semester_id
INNER JOIN office_hours
ON schedule.id = office_hours.schedule_id AND faculty.id = office_hours.faculty_id
This query gets info from all the tables you have in your graph, aside from the event table, that isn't related to any other. But still this query should have more fields on the SELECT (you are only selection fields from the class table, I understand you'd want data from the other 10 tables as well), to do this simple add 'tablename.field' to the list of fields from the SELECT.
I have Doctrine2 DQL query but I want to build it with QueryBuilder, I have noticed that produced DQL is somewhat different from the handcrafted one, and I'm wondering what am I missing here - maybe I'm not aware of something or doing things wrong way?
Ok, some details:
My handcrafted query looks like this:
select count(fi.id)
from Entities\Content\FolderLookup fl
join fl.site fls
join fl.folder flf,
Entities\Content\FolderItem fi
join fi.site fis
join fi.folder fif
join fi.item it
join it.type tp
join it.content ic
where fl.namePath = ?1
and tp.name = ?2
and fls.id = fis.id
and flf.id = fif.id
Now, I'm trying to reproduce it like this with QueryBuilder:
$qb->select("count(fi.id)")->from("Entities\Content\FolderLookup", "fl")->join("fl.site","fls")->join("fl.folder", "flf");
$qb->from("Entities\Content\FolderItem","fi")->join("fi.site","fis")->join("fi.folder","fif");
$qb->join("fi.item","it")->join("it.type","tp")->join("it.content","ic");
$wherePart = $qb->expr()->andx();
$wherePart->add($qb->expr()->eq("fl.namePath","?1"));
$wherePart->add($qb->expr()->eq("tp.name","?2"));
$wherePart->add($qb->expr()->eq("fls.id","fis.id"));
$wherePart->add($qb->expr()->eq("flf.id","fif.id"));
$qb->where($wherePart);
This however is producing this DQL query:
SELECT count(fi.id) FROM Entities\Content\FolderLookup fl,
Entities\Content\FolderItem fi
INNER JOIN fl.site fls
INNER JOIN fl.folder flf
INNER JOIN fi.site fis
INNER JOIN fi.folder fif
INNER JOIN fi.item it
INNER JOIN it.type tp
INNER JOIN it.content ic
WHERE (fl.namePath = ?1)
AND (tp.name = ?2)
AND (fls.id = fis.id)
AND (flf.id = fif.id)
As you can see there is part of this missing comapring to handcrafted one (First line):
fl join fl.site fls join fl.folder flf
I'm not sure why these joins are missing as I am defining them here:
$qb->select("count(fi.id)")->from("Entities\Content\FolderLookup", "fl")->join("fl.site","fls")->join("fl.folder", "flf");
Update:
The fun part starts, when DQL gets translated into SQL - in this case MySQL:
Handcrafted one becomes:
SELECT count(f0_.id) AS sclr0 FROM FolderLookup f1_ INNER JOIN Site s2_ ON f1_.site_id = s2_.id INNER JOIN Folder f3_ ON f1_.folder_id = f3_.id, FolderItem f0_ INNER JOIN Site s4_ ON f0_.site_id = s4_.id INNER JOIN Folder f5_ ON f0_.folder_id = f5_.id INNER JOIN Item i6_ ON f0_.item_id = i6_.id INNER JOIN ItemType i7_ ON i6_.type_id = i7_.id INNER JOIN ItemContent i8_ ON i6_.content_id = i8_.id WHERE f1_.namePath = ? AND i7_.name = ? AND s2_.id = s4_.id AND f3_.id = f5_.id
Where generated one looks like this:
SELECT count(f0_.id) AS sclr0 FROM FolderLookup f1_, FolderItem f0_ INNER JOIN Site s2_ ON f1_.site_id = s2_.id INNER JOIN Folder f3_ ON f1_.folder_id = f3_.id INNER JOIN Site s4_ ON f0_.site_id = s4_.id INNER JOIN Folder f5_ ON f0_.folder_id = f5_.id INNER JOIN Item i6_ ON f0_.item_id = i6_.id INNER JOIN ItemType i7_ ON i6_.type_id = i7_.id INNER JOIN ItemContent i8_ ON i6_.content_id = i8_.id WHERE (f1_.namePath = ?) AND (i7_.name = ?) AND (s2_.id = s4_.id) AND (f3_.id = f5_.id)
And this is invalid statement, as database returns with:
Column not found: 1054 Unknown column 'f1_.site_id' in 'on clause'
Any ideas welcome.
It seems the DQL parser is wrongly positioning the joins to the wrong from.
My initial suggestion is to try to make only 1 FROM item and a subselect.
Also, I'd love if you add the same content you asked here in our bug tracking: http://www.doctrine-project.org/jira/browse/DDC
Thanks a lot!
Guilherme Blanco
Doctirne Core Developer
they are not missing. just reordered
INNER JOIN fl.site fls
INNER JOIN fl.folder flf