SELECT语句中的交叉匹配表

时间:2014-05-15 12:56:03

标签: php mysql pdo

我有table1和table2。在两个表中,1字段是comon。 例: table1' name'字段值与table2' studentname'相同字段值。

现在我希望能够通过SELECT查询中的交叉匹配来获取数据。

表1

name  |  subject  | 
------+-----------+
Kyle  |  Science  |
John  |  Science  | 
Peter |  Maths    | 

表2

score  |  studentname
-------+-------------
78     | John
89     | Kyle
83     | Peter

这是我到目前为止所做的。没有运气。

    foreach ($my_con->query("SELECT subject, examDate, table1.name, score, studentname FROM table1 JOIN table2 ON table1.name = table2.studentname SORT BY table2.score DESC") as $result){
            $gtname = $result['name'];
            $gtsubject = $result['subject'];
            $gtScore = $result['score'];
            $gtTIme = $result['date'];

}         };

我希望回声是这样的:

Kyle   Science  89
JOHN   Science  78

4 个答案:

答案 0 :(得分:0)

查询中的结束报价位置可能会导致错误。改变这个 -

foreach ($my_con->query("SELECT subject, table1.name, score, studentname FROM table1 JOIN table2 ON table1.name = table2.studentname" SORT BY table2.score DESC) as $result){

到此 -

foreach ($my_con->query("SELECT subject, table1.name, score, studentname FROM table1 JOIN table2 ON table1.name = table2.studentname SORT BY table2.score DESC") as $result){

答案 1 :(得分:0)

您的查询中有"个错误的位置。应该是:

$my_con->query("SELECT subject, table1.name, score, studentname FROM table1 JOIN table2 ON table1.name = table2.studentname SORT BY table2.score DESC"

答案 2 :(得分:0)

首先,了解您是否收到语法错误,SQL错误等有助于提供最准确的指导。

我没有仔细检查语法,但是,假设您正在使用mysqli并且您正确创建了数据库连接对象,则需要在取消引用数组内容之前将结果作为关联列表获取:< / p>

$response = $my_con->query("SELECT subject, name, score from table1, table2 where name=studentname order by score DESC");

foreach ($response->fetch_assoc() as $result) {
    $gtname = $result['name'];
    $gtsubject = $result['subject'];
    $gtScore = $result['score'];
    echo ($gtname.$gtsubject.$gtScore);
}

答案 3 :(得分:0)

SORT不是MySql关键字。您可能想要使用ORDER。 尝试使用数据库调试查询。如果你的查询不起作用,php代码只会分散注意力。