How to retrieve data from mysql database joining 5 different tables - php

I am trying to retrieve data from mysql database from 5 different table but it did not work as it should and it did not display anything.
tables are :
site_info
site_coordinates
owner_info
subcontractor_info
company_info
site_info:
siteID
companyID
-siteNAME
ownerID
subcontractorID
equipmentTYPE
site coordinates:
siteID
latitude
longitude
height
owner_info:
ownerID
ownerNAME
ownerCONTACT
subcontractor_info:
subcontractorID
subcontractorCOMPANY
subcontractorNAME
subcontractorCONTACT
company_info:
companyID
companyNAME
mysql query:
select
site_info.siteID,site_info.siteNAME ,site_info.equipmentTYPE,site_coordinates.latitude,site_coordinates.longitude,site_coordinates.height ,owner_info.ownerNAME,owner_info.ownerCONTACT,company_info.companyNAME,subcontractor_info.subcontractorCOMPANY,subcontractor_info.subcontractorNAME,subcontractor_info.subcontractorCONTACT
from `site_info`
INNER JOIN `owner_info`
on site_info.ownerID = owner_info.ownerID
INNER JOIN `company_info`
on site_info.companyID = company_info.companyID
INNER JOIN `subcontractor_info`
on site_info.subcontractorID = subcontractor_info.subcontractorID
INNER JOIN `site_coordinates`
on site_info.siteID=site_coordinates.site_id
where owner_info.ownerID = 159
Where is my error, and is there any better way to do it?

I solve it just needed to change to the LEFT JOIN .
so the updated query looks:
select
site_info.siteID,site_info.siteNAME ,site_info.equipmentTYPE,site_coordinates.latitude,site_coordinates.longitude,site_coordinates.height ,owner_info.ownerNAME,owner_info.ownerCONTACT,company_info.companyNAME,subcontractor_info.subcontractorCOMPANY,subcontractor_info.subcontractorNAME,subcontractor_info.subcontractorCONTACT from `site_info`
LEFT JOIN `owner_info`
on site_info.ownerID = owner_info.ownerID
LEFT JOIN `company_info`
on site_info.companyID = company_info.companyID
LEFT JOIN `subcontractor_info`
on site_info.subcontractorID = subcontractor_info.subcontractorID
LEFT JOIN `site_coordinates`
on site_info.siteID=site_coordinates.siteID
where owner_info.ownerID = 159
thank you for your comments and answers

The Query is syntactically correct. Since you are facing output problems check your Relation Algebra. Are you using the right JOIN conditions between them? If each of the two tables has a common attribute you can perform Natural Join ie without giving conditions, the common attribute will be sorted out and I would write such complex queries using ALIAS 'AS' keyword.
SELECT
site_info.siteID,
site_info.siteNAME,
site_info.equipmentTYPE,
site_coordinates.latitude,
site_coordinates.longitude,
site_coordinates.height,
owner_info.ownerNAME,
owner_info.ownerCONTACT,
company_info.companyNAME,
subcontractor_info.subcontractorCOMPANY,
subcontractor_info.subcontractorNAME,
subcontractor_info.subcontractorCONTACT
FROM `site_info` AS SI JOIN `owner_info` AS OI
ON SI.ownerID = OI.ownerID
JOIN `company_info` AS CI
ON SI.companyID = CI.companyID
JOIN `subcontractor_info` AS SUBI
ON SI.subcontractorID = SUBI.subcontractorID
JOIN `site_coordinates` AS SC
ON SI.siteID=SC.site_id
WHERE owner_info.ownerID = 159;

Related

Attempting to add count function to a complex query PHP MYSQL

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;

how to display records as empty if data not present in table using left join

SELECT MH.Home_Address_Id,MH.Member_Id,MH.First_Name,MH.Middle_Name,
MH.Last_Name,MH.Address AS Preferred_Address,MH.City AS Preferred_City,
MH.State AS Preferred_State,MH.Zip ASPreferred_Zip,MH.Nickname,
MH.Phone,MH.Mobile,MH.Email,
(CASE WHEN MH.Preferred=0 THEN 'Work Address'
WHEN MH.Preferred=1 THEN 'Home Address' END)AS Preferred,
(CASE WHEN MP.Status=0 THEN 'Current'
WHEN MP.Status=1 THEN 'Past due'
WHEN MP.Status=2 THEN 'Paid' END)AS Status,
MP.Payment_Amount,MP.Payment_Date,MT.Admiral_Title,MT.Spouse_Title,
MT.Couple_Title,MS.First_Name AS Spouse_name,
MS.Nickname AS Spouse_Nickname,
MS.Email AS Spouse_Email,sca.SubCategory_Name AS Admiral_Type_Id,
scr.SubCategory_Name AS Royalty_Type_Id,
scp.SubCategory_Name AS Parent_Type_Id,
scg.SubCategory_Name AS Guest_Type_Id,
MM.Member_Note, g.Guest_Name AS Guest_Of
FROM
member_home_address MH,
member_payment_master MP,
member_mailing_title MT,
member_spouse_info MS,
member_master MM,
LEFT JOIN guest g ON g.Member_Id = MM.Member_Id
LEFT JOIN member_subcategory sca ON sca.SubCategory_Id = MM.Admiral_Type_Id
LEFT JOIN member_subcategory scr ON scr.SubCategory_Id = MM.Royalty_Type_Id
LEFT JOIN member_subcategory scp ON scp.SubCategory_Id = MM.Parent_Type_Id
LEFT JOIN member_subcategory scg ON scg.SubCategory_Id = MM.Guest_Type_Id
WHERE MH.Member_Id IN
(1,2,3,4,6,7,9,10,11,13,14,16,17,18,19,20,21,22,23,24,25,26,29,31,33,34,35,36,37,38,39,40,41 ,44,45,46,47,48,49,52,53,55,57,58,59,61,62,63,64,65,66,67,68,69,70,71,72,73,75,76,78,80,81,
87,88,89,91,92,93,94,95,96,97,98,99,100,101,102,103,104,106,107,108,109,111,113,115,116,117,
118,119,121,122,123,124,128,129,130,131,133,134,135,136,137,138,139,140,141,143,145,146,148,
149,150,151,152,153,155,156,158,159,160,163,164,166,167,169,170,171,172,173,174,177,179,180,
181,182,183,185,186,187,189,191,192,193,194,196,198,199,202,205,206,209,210,211,212,213,214,
217,218,219,221,222,223,224,227,228,229,231,234,235,236,238,239,240,243,245,246,247,248,249,
251,252,253,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,274,275,277,
280,281,284,285,286,287,289,290,291,292,294,295,296,298,300,301,302,303,304,305,307,308,310,
311,313,314,315,316,318,320,321,322,323,324,325,327,328,331,332,334,336,337,338,339,341,343,
344,345,346,347,348,350,351,352,353,354,355,356,357,358,359,361,931,934,935,936,937,938,939,
940,941,942,944,945,946,947,948,950,951,952,1431,1432,1433,1434,1435,1436,1437,1438,1439,144
0,1441,1442,1443,1444,1445,1446,1447,1448,1449,1450,1451,1452,1453,1454,1455,1986,1987,1988,
1989,1990,1991,1992,1993,1994,1995,1996,3168,3164,3142,3143,3144,3154,3155,3156,3157,3158,
3159,3160,3161,3162,3165,3167)
AND MH.Member_Id = MP.Member_Id
AND MH.Member_Id = MT.Member_Id
AND MP.Member_Id = MS.Member_Id
AND MP.Member_Id = MM.Member_Id
here for the member_id '10' we don't have record in the member_spouse_info table.It is skipping the total member_id. How can we get the data of member_id 10.using the above query? Why is it omitting certain rows?
You are unfortunately combining the old-time list-of-tables / WHERE id=id syntax with the newer and more effective LEFT JOIN syntax.
FROM member_home_address MH, ...
member_spouse_info MS ...
WHERE ... MH.Member_Id = MS.Member_Id
is the equivalent of an INNER JOIN. So, the absent record in MS is suppressing the whole result set record.
You want this instead
FROM member_master MM
LEFT JOIN member_payment_master MP ON MM.Member_Id = MP.Member_Id
LEFT JOIN member_mailing_title MT ON MM.Member_Id = MT.Member_Id
LEFT JOIN member_spouse_info MS ON MM.Member_Id = MS.Member_Id
LEFT JOIN member_home_address MH ON MM.Member_Id = MH.Member_Id
LEFT JOIN guest g ON g.Member_Id = MM.Member_Id
LEFT JOIN member_subcategory sca ON sca.SubCategory_Id = MM.Admiral_Type_Id
LEFT JOIN member_subcategory scr ON scr.SubCategory_Id = MM.Royalty_Type_Id
LEFT JOIN member_subcategory scp ON scp.SubCategory_Id = MM.Parent_Type_Id
LEFT JOIN member_subcategory scg ON scg.SubCategory_Id = MM.Guest_Type_Id
Then, get rid of these WHERE clauses. You've moved them into the LEFT JOIN syntax. If you leave them in place they convert the LEFT JOIN operations into INNER JOIN operations.
AND MH.Member_Id = MP.Member_Id /*delete these!*/
AND MH.Member_Id = MT.Member_Id
AND MP.Member_Id = MS.Member_Id
AND MP.Member_Id = MM.Member_Id
I started this join list with member_master on the assumption that it actually contains one row for each member, and should drive the rest of the join.
Your query, for some reason I don't know, selects the rows and drives the JOIN cascade based on the rows in member_home_address. You may want to try driving it with
WHERE MM.Member_ID IN (/*dirty great list of member ids*/)
instead.
If I were you I'd troubleshoot this query by building it up join table by join table. You're the only one in possession of the data; StackOverflow can't help you find missing records.

Using multiple tables inner join on one key item. Can't figure out what is wrong

For the life of me I can not figure out where I have went wrong
I am pulling the data from these multiple tables but no data appearing
$result=mysql_query("SELECT * FROM chars uc
INNER JOIN zone_settings t ON uc.pos_zone = t.zoneid
INNER JOIN char_look v ON uc.charid = v.charid
INNER JOIN char_jobs y ON uc.charid = y.charid
INNER JOIN char_stats n ON uc.charid = n.charid
INNER JOIN char_profile p ON uc.charid = p.charid
WHERE `accid`='".$user["id"]."' ORDER BY `charid`");
Thanks kwolfe using LEFT JOIN and Removing the ORDER BY it works now. Here is the code.
$result=mysql_query("SELECT * FROM chars uc
LEFT JOIN zone_settings t ON uc.pos_zone = t.zoneid
LEFT JOIN char_look v ON uc.charid = v.charid
LEFT JOIN char_jobs y ON uc.charid = y.charid
LEFT JOIN char_stats n ON uc.charid = n.charid
LEFT JOIN char_profile p ON uc.charid = p.charid
WHERE `accid`='".$user["id"]."'");
Switch to LEFT JOINS to see if your missing a relationship along the way (INNER JOIN will only show data where a relationship is made for each table, in this case ALL tables.)

Get data from all tables in database

Ok I have 5 tables in my database they are as follows
officelocations_tbl
state_tbl
city_tbl
staff_tbl
titles_tbl
The titles table is only associated with the staff table but the others are all inner joined. I have tried various mysql statements but none are allowing me to bring in the titles_tbl.
here is the latest version of the sql statement I am attempting to use:
SELECT officelocations_tbl.*,city_tbl.*, state_tbl.* , titles_tbl.*,
contact1.firstName AS c1Firstname, contact1.lastName AS c1lastName,
contact1.middleInitial AS c1middleInitial, contact1.suffix AS c1suffix,
contact1.accredations AS c1accredations, contact1.phone AS c1Phone,
contact1.faxNumber AS c1FaxNumber, contact1.mobilePhone AS c1Mobile,
contact1.email AS c1Email, contact1.titleID AS c1Title,
contact2.firstName AS c2Firstname, contact2.lastName AS c2lastName,
contact2.middleInitial AS c2middleInitial, contact2.suffix AS c2suffix,
contact2.accredations AS c2accredations, contact2.phone AS c2Phone,
contact2.faxNumber AS c2FaxNumber, contact2.mobilePhone AS c2Mobile,
contact2.email AS c2Email, contact2.titleID AS c2Title,
partner.firstName AS c3Firstname, partner.lastName AS c3lastName,
partner.middleInitial AS c3middleInitial, partner.suffix AS c3suffix,
partner.accredations AS c3accredations, partner.phone AS c3Phone,
partner.faxNumber AS c3FaxNumber, partner.mobilePhone AS c3Mobile,
partner.email AS c3Email, partner.titleID AS c3Title
FROM officelocations_tbl
JOIN city_tbl ON (officelocations_tbl.cityID = city_tbl.cityID)
INNER JOIN titles_tbl ON titles_tbl.titleID = staff_tbl.titleID
LEFT OUTER JOIN state_tbl ON (officelocations_tbl.stateID = state_tbl.stateID)
LEFT OUTER JOIN staff_tbl contact1 ON (contact1.staffID = officelocations_tbl.contact1)
LEFT OUTER JOIN staff_tbl contact2 ON (contact2.staffID = officelocations_tbl.contact2)
LEFT OUTER JOIN staff_tbl partner ON (partner.staffID = officelocations_tbl.partner)
However this gives me an error [Err] 1054 - Unknown column 'staff_tbl.titleID' in 'on clause'. If I remove both the lines:
INNER JOIN titles_tbl ON titles_tbl.titleID = staff_tbl.titleID
titles_tbl.*,
it works but doesn't pull in the title. I have tried doing it this way as well but then it only pulls in the title once and not for all three contacts.
SELECT
staff_tbl.staffID,
staff_tbl.staffID_C2,
staff_tbl.staffID_P,
staff_tbl.firstName,
staff_tbl.middleInitial,
staff_tbl.lastName,
staff_tbl.suffix,
staff_tbl.accredations,
staff_tbl.email,
staff_tbl.phone,
staff_tbl.mobilePhone,
staff_tbl.officePhone,
staff_tbl.faxNumber,
staff_tbl.address1,
staff_tbl.address2,
staff_tbl.cityID,
staff_tbl.stateID,
staff_tbl.zipCode,
staff_tbl.titleID,
staff_tbl.locationID,
staff_tbl.photoURL,
staff_tbl.vCardURL,
staff_tbl.qRCodeURL,
staff_tbl.resumeURL,
staff_tbl.biography,
staff_tbl.dateCreated,
officelocations_tbl.locationID,
officelocations_tbl.officeName,
officelocations_tbl.address1,
officelocations_tbl.address2,
officelocations_tbl.cityID,
officelocations_tbl.stateID,
officelocations_tbl.zipCode,
officelocations_tbl.officePhone,
officelocations_tbl.contact1,
officelocations_tbl.contact2,
officelocations_tbl.partner,
city_tbl.cityID,
city_tbl.cityName,
state_tbl.stateID,
state_tbl.state_abreviation,
state_tbl.state_name,
titles_tbl.titleID,
titles_tbl.titleName,
contact1.firstName AS c1Firstname, contact1.lastName AS c1lastName,
contact1.middleInitial AS c1middleInitial, contact1.suffix AS c1suffix,
contact1.accredations AS c1accredations, contact1.phone AS c1Phone,
contact1.faxNumber AS c1FaxNumber, contact1.mobilePhone AS c1Mobile,
contact1.email AS c1Email, contact1.titleID AS c1Title,
contact2.firstName AS c2Firstname, contact2.lastName AS c2lastName,
contact2.middleInitial AS c2middleInitial, contact2.suffix AS c2suffix,
contact2.accredations AS c2accredations, contact2.phone AS c2Phone,
contact2.faxNumber AS c2FaxNumber, contact2.mobilePhone AS c2Mobile,
contact2.email AS c2Email, contact2.titleID AS c2Title,
partner.firstName AS c3Firstname, partner.lastName AS c3lastName,
partner.middleInitial AS c3middleInitial, partner.suffix AS c3suffix,
partner.accredations AS c3accredations, partner.phone AS c3Phone,
partner.faxNumber AS c3FaxNumber, partner.mobilePhone AS c3Mobile,
partner.email AS c3Email, partner.titleID AS c3Title
FROM officelocations_tbl
INNER JOIN staff_tbl ON staff_tbl.staffID = officelocations_tbl.contact1
INNER JOIN state_tbl ON state_tbl.stateID = officelocations_tbl.stateID
INNER JOIN titles_tbl ON titles_tbl.titleID = staff_tbl.titleID
INNER JOIN city_tbl ON city_tbl.cityID = officelocations_tbl.cityID
LEFT OUTER JOIN staff_tbl contact1 ON (contact1.staffID = officelocations_tbl.contact1)
LEFT OUTER JOIN staff_tbl contact2 ON (contact2.staffID = officelocations_tbl.contact2)
LEFT OUTER JOIN staff_tbl partner ON (partner.staffID = officelocations_tbl.partner)
This will only pull for the first association of staff_tbl.staffID = officelocations_tbl.contact1. I am stumped as to what to try next. Is there anyone who would know how to get it to pull all 5 tables?
You just need to move your INNER JOIN down lower, e.g. from
INNER JOIN titles_tbl ON titles_tbl.titleID = staff_tbl.titleID
LEFT OUTER JOIN state_tbl ON (officelocations_tbl.stateID = state_tbl.stateID)
to
LEFT OUTER JOIN state_tbl ON (officelocations_tbl.stateID = state_tbl.stateID)
INNER JOIN titles_tbl ON titles_tbl.titleID = staff_tbl.titleID
At the time the parser reaches the INNER JOIN, staff_tbl has not yet been joined, and the parser will not "look ahead" to see if it's joined later. So it immediately bails with a "no such table/field".
Switching the order in which this occurs allows taff_table to be joined in first, and then you can use it in further joins.

Doctrine 2 QueryBuilder vs Handcoded DQL - different results

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

Categories