[英]How to use inner join on a MySQL table using PHP?
我有兩張這樣的表:
員工
EmployeeID EmployeeName
1234 Jessica
1235 Tiffany
1236 Kayla
1237 Jackson
1238 Junior
1239 Ray
1240 Raymond
和...
形式
IDForm Form_EmployeeID Content AgreementBy Verificationby Validateby receiver
1 1234 abcde 1235 1236 1237 1240
2 1238 dcbe 1235 1239 1237 1240
問題是,我想顯示這樣的數據:
我試過使用這個代碼:
$id=$_GET['id'];
$sql=mysql_query("SELECT Employee.*, Form.*
FROM Form
INNER JOIN Employee ON Form.Form_EmployeeID= Employee.EmployeeID
where Form.FormID = '$id'") or die(mysql_error()); $data=mysql_fetch_array($sql);
但是數據看起來就像這樣:
Form ID : 1
Employee Name : Jessica
Content : abcde
Agreement By :
Verification By:
Validate By :
Received By :
或者像這樣:
Form ID : 1
Employee Name : Jessica
Content : abcde
Agreement By : 1235
Verification By: 1236
Validate By : 1237
Received By : 1240
我可以知道錯誤在哪里嗎?
你的查詢是這樣的......
SELECT Form.*,
a.EmployeeName as employee_name,
b.EmployeeName as agreement_by,
c.EmployeeName as verification_by,
d.EmployeeName as validate_by,
e.EmployeeName as receiver_by
FROM Form
LEFT JOIN Employee a ON Form.Form_EmployeeID= a.EmployeeID
LEFT JOIN Employee b ON Form.AgreementBy= b.EmployeeID
LEFT JOIN Employee c ON Form.Verificationby= c.EmployeeID
LEFT JOIN Employee d ON Form.Validateby= d.EmployeeID
LEFT JOIN Employee e ON Form.receiver= e.EmployeeID
where Form.FormID = '$id'
試試這個查詢,不要在選擇查詢中使用“*” ...
SELECT f.IDForm , f.Content ,
emp1.EmployeeName as employee_name,
emp2.EmployeeName as agreement_by,
emp3.EmployeeName as verification_by ,
emp4.EmployeeName as validate_by,
emp5.EmployeeName as receiver_by
FROM Form f
INNER JOIN Employee emp1 ON emp1.Form_EmployeeID= f.EmployeeID
INNER JOIN Employee emp2 ON emp2.AgreementBy= f.EmployeeID
INNER JOIN Employee emp3 ON emp3.Verificationby= f.EmployeeID
INNER JOIN Employee emp4 ON emp4.Validateby= f.EmployeeID
INNER JOIN Employee emp5 ON emp5.receiver= f.EmployeeID
where Form.FormID = '$id'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.