简体   繁体   中英

Getting record from second table row in mysql

I have 2 table with the same field name and i want to display record from the two field columns.

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>";

I want the result to be Adam -various -record for example.That is I want the third echo "<p><b>". $row['test'] ."</b></p>"; "<p><b>". $row['test'] ."</b></p>"; to display record from table_b.

Thanks

You can use SQL alias

SELECT column_name AS alias_name

Example from your code

$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"))."'";

Try this:

$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>";

Note that I have written a.user like b.user . a.user like b is wrong.

user the below query

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()

it will return result like below

在此处输入图片说明

think it will solve your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM