How to echo values from the same field of the related table - php

I have two related tables: Contracts with 3 columns: ContractsID, AreaManager and AreaLeader. Then I have Employees table with 2 columns: EmployeesID, EmployeeName. The EmployeeID is both foreign key for AreaManager and AreaLeader. I am trying to create a SELECT query to echo ContractID, Area Manager's name and Area Leader's name.
This is what I have;
$query = "SELECT Contracts.ContractsID, Contracts.AreaLeader, Contracts.AreaManager, Employees.EmployeeName FROM Contracts
INNER JOIN Employees ON Employees.EmployeeID = Contracts.AreaManager
INNER JOIN Employees ON Employees.EmployeeID = Contracts.AreaLeader
However, the query doesn't work. I believe that I should use table aliases but I kind of struggling with this.
I tried this but it didn't work:
$query = "SELECT c.ContractsID, m.Employees.EmployeeName as ManagerName, l.Employees.EmployeeName as LeaderName
FROM c.Contracts
JOIN Employees m ON m.EmployeeID = c.AreaManager
JOIN Employees l ON l.EmployeeID = c.AreaLeader
Any help would be greatly appreciated!

The reason why your original query does not work is because you join with Employees twice, and you need to alias them to make a distinction.
$query = "SELECT Contracts.ContractsID, Contracts.AreaLeader, Contracts.AreaManager, Employees.EmployeeName FROM Contracts
INNER JOIN Employees Employee1 ON Employee1.EmployeeID = Contracts.AreaManager
INNER JOIN Employees Employee2 ON Employee2.EmployeeID = Contracts.AreaLeader
You do not need to alias Contracts unless you want to do so.
Your second query fails because you did not alias Contracts properly. You should have put Contracts c instead of c.Contracts.

You have the correct approach on your second query, but you have syntax error in it. your query would look something like this:
$query = "SELECT c.ContractsID, m.EmployeeName as ManagerName, l.EmployeeName as LeaderName
FROM Contracts c
JOIN Employees m ON m.EmployeeID = c.AreaManager
JOIN Employees l ON l.EmployeeID = c.AreaLeader"

Related

How do i combine 3 tables in one query in php

Hi guys how do i combine this 3 tables in one single query in php?
PHP
<?php
$db_name = "atfest_db";
$mysql_user = "root";
$mysql_pass = "";
$server_name = "localhost";
$sql = "SELECT teamone,teamtwo,s_name FROM sport as A right join matches
as B right join schedule as C ON A.s_id = B.s_id ORDER by m_id asc";
$con = mysqli_connect($server_name,$mysql_user,$mysql_pass,$db_name);
$result = mysqli_query($con,$sql);
$response = array();
while($row=mysqli_fetch_array($result))
{
array_push($response, array("teamone"=>$row[0], "teamtwo"=>$row[1],
"s_name"=>$row[2]));
}
echo json_encode (array("schedule_response"=>$response));
mysqli_close($con);
?>
Sport table is connected to matches b s_id while matches table is connected to schedule table by m_id
Matches Table
Schedule Table
Sport Table
You can join two or more table using join() in mysql like:
select t1.col1, t2.col2
FROM table1 as t1 JOIN table2 as t2
on t1.some_col = t2.some_col // where t1, t2 have a common column on which joining is done
where condition;
Reference
Try this SQL-statement instead:
SELECT B.teamone,B.teamtwo,A.s_name
FROM sport A
LEFT JOIN matches B
LEFT JOIN schedule C
ON A.s_id = B.s_id
ORDER by C.m_id asc
SELECT teamone,teamtwo,s_name FROM sport A
LEFT JOIN matches B ON A.m_id=B.m_id
LEFT JOIN schedule C ON A.s_id = B.s_id ORDER by A.m_id asc
Hi this is the right query for you . You are getting error because you are not using right query..
SELECT teamone,teamtwo,s_name FROM sport as A right join matches as B ON A.s_id = B.s_id right join schedule as C ON B.m_id = C.m_id order by B.m_id asc
Now you can go through it to get the appropriate result .This query is generated according to your schema.
SELECT `schedule`.`id`, (and other relevant fields from schedule table), `matches`.`m_id`, `matches`.`teamone`, `matches`.`teamtwo`, (and other relevant fields from matches table), `sport`.`s_id`, (and other relevant fields from sport table)
FROM `sport`
RIGHT JOIN `matches` ON `matches`.`s_id` = `sport`.`s_id`
RIGHT JOIN `schedule` ON `schedule`.`m_id` = `matches`.`m_id`
ORDER BY `schedule`.`id`
The above query will solve your basic question of combining three tables. But this is a bad practice. There will be a lot of redundant data. You're selecting only three column. In that, there is no index also. You can't figure out how each row is different from one another. Please mention the purpose or the logic of the query. So that we can fine tune the query accordingly.
Update
I've updated the columns which we are selecting in the query. Now there is a unique column schedule id to uniquely identify each row. You can select other columns also depends upon the necessity.

Merging two queries with the same binded parameter

I have a first SQL query getting a table with id_member as parameter
$stmt = $mysqli -> prepare("SELECT a.id_alerte,
a.nom_alerte,
ar.id_roster,
r.nom_roster,
FROM alerte a,
alerte_par_roster ar,
roster_par_membre rm
INNER JOIN roster r
ON r.id_roster = rm.id_roster
WHERE rm.id_roster = ar.id_roster
AND ar.id_alerte = a.id_alerte
AND rm.id_membre = ?");
$stmt->bind_param('i', $id_membre);
I need to insert a second query counting the number of lines in another table.
The second query is:
"SELECT COUNT(DISTINCT id_roster)
FROM disponibilites_par_member_alertes
WHERE id_member = ?
AND id_alerte = ?"
As you can notice id_member is the identical in both queries but id_alerte (used as a parameter of the second query is a result of a first query).
I hope I am clear.
Any idea will be very welcome
I don't fully understand what your queries are intended to do. It would help to have clear information on the table structure and what each of the fields represents. I've tried to make a guess based on the table names but can't be certain it's correct.
The first thing I did was just to transform your WHERE condition such that each of the tables are joined explicitly. This is just for readability.
SELECT
a.id_alerte,
a.nom_alerte,
ar.id_roster,
r.nom_roster
FROM alerte a
INNER JOIN alerte_par_roster ar
ON ar.id_alerte = a.id_alerte
INNER JOIN roster_par_membre rm
ON rm.id_roster = ar.id_roster
INNER JOIN roster r
ON r.id_roster = rm.id_roster
WHERE
rm.id_membre = ?
Now we combine with the other query:
SELECT
a.id_alerte,
a.nom_alerte,
ar.id_roster,
r.nom_roster,
rc.id_roster_count
FROM alerte a
INNER JOIN alerte_par_roster ar
ON ar.id_alerte = a.id_alerte
INNER JOIN roster_par_membre rm
ON rm.id_roster = ar.id_roster
INNER JOIN roster r
ON r.id_roster = rm.id_roster
LEFT JOIN (
SELECT id_membre, id_alerte, COUNT(DISTINCT id_roster) AS id_roster_count
FROM disponibilites_par_member_alertes
GROUP BY id_membre, id_alerte
) AS rc
ON rc.id_membre = rm.id_membre
AND rc.id_alerte = ar.id_alerte
WHERE
rm.id_membre = ?
With my own generated data I get results like this:
If this is not enough to solve the problem you will need to provide more details about the tables and the design.

Is there a better way to get info from 2 tables

In database the users have a row called weapon_id which determines what weapon he uses from another table with weapons.
Is there a better way to get that info like join table or something?
$user_get = mysqli_query($db, "SELECT * FROM members WHERE id = '".$_SESSION['sess_id']."'");
$user = mysqli_fetch_assoc($user_get);
$weapon_get = mysqli_query($db, "SELECT * FROM weapons WHERE weapon_id = '".$user['weapon_id']."'");
$weapon = mysqli_fetch_assoc($weapon_get);
use a join like this
$user_get = mysqli_query($db, "SELECT * FROM members m LEFT JOIN weapons w ON(w.weapon_id=m.weapon_id) WHERE m.id = '".$_SESSION['sess_id']."'");
$user = mysqli_fetch_assoc($user_get);
change the join type as per your requirement. the above query for only example
INNER JOIN: Returns all rows when there is at least one match in BOTH
tables
LEFT JOIN: Return all rows from the left table, and the matched rows
from the right table
RIGHT JOIN: Return all rows from the right table, and the matched
rows from the left table
FULL JOIN: Return all rows when there is a match in ONE of the tables
more about join click here
AND also check this http://blog.codinghorror.com/a-visual-explanation-of-sql-joins/
SELECT * FROM `weapon` as w
JOIN `user` as u
on w.weapon_id = u.weapon_id
and u.id = :session_id
How about this ?

Search in two mysql tables with non identical tables (keyword search)

I want to make my keyword search in two mysql tables. my tables don't have any identical column names. But I tried few queries, they didn't work for me.
Keyword IS 07731A0328
I tried this:
$sql = "select a.*, b.* from table1 a inner join table2 b on a.col1=b.htno WHERE a.col1 like '$name'";
$sql = "select a.*, b.* from table1 a join table2 b on a.col1=b.htno WHERE a.col1 like $name";
Can someone help me with this? Thank you!
TABLE 1
TABLE2
Join is your friend:
http://www.w3schools.com/sql/sql_join.asp
Combine rows from two or more tables, based on a common field between them.
SELECT * FROM TABLE1 INNER JOIN TABLE2 ON TABLE1.col1=TABLE2.htnon
WHERE TABLE1.col1 = "07731A0328"
The query will be
SELECT * FROM Table1,Table2
WHERE Table1.col1=Table2.htnon AND Table1.col1 = "07731A0328"

MySQL, Find all employees of a "manager"

I have a "manager" that can be assigned to many locations and handles one department in every location. I want a query that can grab all of this:
http://sqlfiddle.com/#!2/33453c/1
In the example above (in the link) you can see I have calculated how many employees are in each department.
Managers and Employees are in a table named staff, I do not want the query to retrieve the manager record(s). So user_role = "Employee";
I run this as a raw query in laravel so I can retrieve them as objects:
$employees= DB::query('query goes in here')->get();
An example would be the manager with staff_id '5' get every employee that is in all of the locations and department the manager is part of if that makes sense?
My guess would be:
Pseudo
First Query SELECT ALL FROM staff, locations and departments where user_role = "employee"
Second Query SELECT ALL FROM staff, locations and departments where manager id=5
Remove all results that do not satisfy the second query but join both queries together?
Help would be greatly appreciated.
I think this is what you want. Left join the manager's department on employee's departments, and get the count of "employee" staff members in each of those departments (even if 0)
Below, shown for manager #2 (you could eliminate the where clause and group by manager id and dept id if you want to see all managers)
SELECT dept.name AS dept, loc.address1 AS loc, emp.*
FROM staff AS mgr
INNER JOIN department_staff AS mgr_dept
ON mgr_dept.staff_id = mgr.staff_id
INNER JOIN departments AS dept
ON mgr_dept.dept_id = dept.dept_id
INNER JOIN location_staff AS mgr_loc
ON mgr_loc.staff_id = mgr.staff_id
INNER JOIN locations AS loc
ON mgr_loc.loc_id = loc.loc_id
INNER JOIN (
SELECT emp.*, dept.dept_id, loc.loc_id
FROM staff AS emp
INNER JOIN department_staff AS dept
ON emp.staff_id = dept.staff_id
INNER JOIN location_staff AS loc
ON emp.staff_id = loc.staff_id
WHERE emp.user_role = "Employee"
) AS emp
ON emp.loc_id = mgr_loc.loc_id
AND emp.dept_id = mgr_dept.dept_id
WHERE mgr.staff_id = 2

Categories