2014-11-21 121 views
-3

我正在嘗試加入一個名爲collegetable的studentdetails表中的dataofbirth列,我需要第二個表中的學生的dataofbirth。以下是我的查詢。加入兩張表

$result = mysqli_query($con,"SELECT `DateofBirth` FROM `studentdetails` INNER JOIN `college` 
    ON `studentdetails`.StudentID = college.StudentID")or die ("Error: ".mysqli_error($con)"); 

所以,當我取回我的第二臺陣列我將能夠得到他們的學生dataofBirth沒有物理連接它們。 任何人都可以發現我的語法有什麼問題嗎?

謝謝

+1

爲什麼它不工作,結果數組是空的還是mysqli拋出並打印錯誤?如果它的情況請讓我們知道,我們可能會幫助你。 – Steini 2014-11-21 11:32:18

+1

哪個表格包含日期分娩?如上所述,在兩個表中?您可以將架構和示例數據粘貼到其中嗎? – SMA 2014-11-21 11:33:15

+0

@Steini不,它只是語法錯誤與myphp你可以點我的語法有什麼問題,除了mysql內查詢內PHP – 2014-11-21 11:34:16

回答

0

它應該是(從註釋:出生日期只在studentdetails存在)

$result = mysqli_query($con,"SELECT sd.DateofBirth FROM studentdetails as sd INNER JOIN college as c 
    ON sd.StudentID = c.StudentID")or die ("Error: ".mysqli_error($con)"); 
+0

什麼是sd?和c? – 2014-11-21 11:39:56

+0

表名的別名(例如 - > studentdetails as sd) – 2014-11-21 11:40:40

+0

謝謝我會試一試:) – 2014-11-21 11:50:07

1

如果你想加入兩個表,你必須提供列的列表從這兩個表都希望包含在合併/組合表中。所以:

試試這個(代[添加其他列..]與其他列位,你可能要包括,注意表的別名是如何被使用它們:

$result = mysqli_query($con,"SELECT s.DateofBirth, c.StudentID, [add other columns from college table here...] FROM studentdetails sd INNER JOIN college c 
    ON sd.StudentID = c.StudentID")or die ("Error: ".mysqli_error($con)"); 

噢,你可能想使用mysqli而不是舊的,不贊成的,醜陋的,緩慢的,不安全的,自殺的想法引發mysql_擴展;)

+0

謝謝,我會試試:) – 2014-11-21 11:49:50

+0

@ Jaek.DI有錯誤,說undefined StudentID,所以我編輯代碼爲$ result = mysqli_query( $ con,「SELECT s.DateofBirth,c.Stude ntID FROM studentdetails sd INNER JOIN college c ON sd.StudentID = c.StudentID WHERE StudentID ='「。 $ _SESSION ['StudentID']。 「'」)或死(「錯誤:」.mysqli_error($ con)「);並且我得到了另一個錯誤錯誤:列'StudentID'中where子句含糊 – 2014-11-21 11:55:41

+0

任何想法請 – 2014-11-21 11:58:48

0

考慮到我們只出生一次(鳳凰除外),學生和他們的出生日期之間的關係是應該是1:1的關係。換句話說,列DateOfBirth可以在college表中聲明。然後選擇自己的出生日期,你簡單的可以這樣做:

select DateOfBirth 
from college 
where StudentID = :id 

不過我看你已經有另外一個表來存儲他們的出生日期,以便你可以做一個連接來選擇自己的出生日期:

select d.DateOfBirth 
from college  c, 
     studentdetails d 
where c.StudentID = d.StudentID; 

或者:

select d.DateofBirth 
from studentdetails d 
inner join college as c 
    on d.StudentID = c.StudentID; 

但高於此查詢將排除學生不從結果studentdetails記錄。要選擇所有學生各自的出生日期,你可以這樣做:

select c.StudentID, 
     s.DateOfBirth 
from studentdetails d 
right join college c 
     on d.StudentID = c.StudentID; 

right join查詢獲取所有的學生,即使他們沒有出生在studentdetails表的日期(right join CMD桌子上大學)。

你可以自由地找出什麼是最適合你的選擇,但我建議你將這個數據模型歸一化,將DateOfBirth列放在college表內。

+0

這裏是我的查詢$結果= mysqli_query($ con,「SELECT s.DateofBirth,c.StudentID FROM studentdetails sd INNER JOIN college c ON sd.StudentID = c.StudentID WHERE StudentID ='「。 $ _SESSION ['StudentID']。 「'」)或死(「錯誤:」.mysqli_error($ CON)「);但仍然得到此錯誤 - 錯誤:列'學生ID'在where子句是含糊的 – 2014-11-21 12:40:55

+0

出生日期只在一個表中聲明,這是學生訂購 – 2014-11-21 12:42:10

+0

@ZinaDweeikat連接SQL查詢確實是非常糟糕的做法,請學習使用[準備好的語句](https://www.youtube.com/watch?v=nLinqtCfhKY)。 – 2014-11-21 12:45:50