2013-05-10 80 views
-1

我有兩個表獲取與PHP(語法)的外鍵

Create TABLE Comment(
    CommentText TEXT, 
    CommentDate DATE NOT NULL, 
    Time time, 
    PostedBy VARCHAR(30), 
    FOREIGN KEY (PostedBy) REFERENCES Employee(Name) 
); 

Create TABLE Employee(
Name VARCHAR(30), 
Title VARCHAR(30), 
Onshift BOOLEAN, 
PRIMARY KEY(Name) 
); 

現在我該怎麼辦下面

$Comments =  mysql_query("SELECT * FROM Comment"); 
$all_comments = array(); 
while($row = mysql_fetch_array($Comments)) { 
    $all_comments[] = $row; 
} 

foreach($all_comments as $commentrow){ 
    if($commentrow['PostedBy']){ //Check if The Employee is Onshift 
     Echo("The employee was on shift"); 
    } 
    else{ 
     Echo("The employee was on shift"); 
    } 
} 

IE給出的外鍵(postedby)查找在另一個值foregin密鑰表(在這種情況下,如果布爾值,如果員工正在轉移?)

回答

0

您的選擇應該是類似於

SELECT c.*, e.Name, e.Onshift FROM Comment as c join Employee as e on c.PostedBy = e.Name 

然後你可以只使用

$commentrow['Onshift'] 
0

可以使用SQL的此評論任何人,測試你的代碼

//Priority on comment table 

$sql = "SELECT cmd.*, emp.* FROM Comment AS cmd 
LEFT JOIN employee AS emp ON cmd.name = emp.name"; 

//use anyone of thsi based on ur need 

$sql = "SELECT cmd.*, emp.* FROM Comment AS cmd 
LEFT JOIN employee AS emp ON emp.name = cmd.name"; 

$Comments =  mysql_query($sql); 
$all_comments = array(); 
while($row = mysql_fetch_array($Comments)) { 

if($row['PostedBy']){ //Check if The Employee is Onshift 
    echo("The employee was on shift"); 
} 
else{ 
    echo("The employee was not in shift"); 
} 
} 
+0

感謝您的回答,希望我能同時接受你的答案:/ – anders 2013-05-10 15:15:05