2014-11-21 123 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