从mysql中的第二个表行获取记录

时间:2013-08-07 06:29:45

标签: php mysql

我有2个具有相同字段名称的表,我想显示两个字段列中的记录。

Table_a
    id date          user    test
    1   2013-08-08   Adam    Various    
    2   2013-08-08   Paul    Record

    Table_b

      id date          user    test
        1   2013-08-08   Adam    Record    
        2   2013-08-08   Paul    Mytest


    $sql = "Select Table_a.date, Table_a.user, Table_a.test, Table_b.date, Table_b.user, Table_b.test FROM table_a, Table_b where Table_a.user like table_b AND table_a.Date = table_b.date AND table_b.Date = '".date("Y-m-d", strtotime("today"))."'";
    $result = mysql_query($sql);
    $row = mysql_fetch_assoc($result); 


 echo "<p'><b>" . $row['user'] . "</b></p>";
 echo "<p><b>". $row['test'] ."</b></p>";
 echo "<p><b>". $row['test'] ."</b></p>";

我希望结果是Adam -various -record例如。那就是我希望第三个echo "<p><b>". $row['test'] ."</b></p>";显示来自table_b的记录。

由于

3 个答案:

答案 0 :(得分:5)

您可以使用SQL别名

SELECT column_name AS alias_name

代码中的示例

$sql = "SELECT Table_a.date AS tableA_date, 
               Table_a.user AS tableA_user,
               Table_a.test AS tableA_test,
               Table_b.date AS tableB_date,
               Table_b.user AS tableB_user, 
               Table_b.test AS tableB_test
        FROM Table_a AS tableA,
             Table_b AS tableB
        WHERE tableA_user
        LIKE tableB 
        AND tableA_date = tableB_date
        AND tableD_date = '".date("Y-m-d", strtotime("today"))."'";

答案 1 :(得分:0)

试试这个:

$sql = "Select
              a.date as adate,
              a.user as auser,
              a.test as atest,
              b.date as bdate,
              b.user as buser,
              b.test as btest
        FROM table_a a, Table_b b
        where 
              a.user like b.user
              AND a.Date = b.date
              AND b.Date = '".date("Y-m-d", strtotime("today"))."'";
echo "<p'><b>" . $row['auser'] . "</b></p>";
echo "<p><b>". $row['atest'] ."</b></p>";
echo "<p><b>". $row['btest'] ."</b></p>";

请注意,我已写过a.user like b.usera.user like b错了。

答案 2 :(得分:0)

使用以下查询

Select table_a.user,table_a.test,table_b.test FROM table_a left join table_b on
table_a.user=table_b.user where table_a.Date = table_b.date AND table_b.Date = curdate()

它将返回如下结果

enter image description here

认为它会解决你的问题。