在mysql PHP中连接表的问题

时间:2014-05-20 15:16:08

标签: php mysql sql jointable

当我使用这个查询时,我的数组中的变量会出现错误 - 如果我使用$ author_slug = $ row ['slug'];而不是$ author_slug = $ row ['authors.slug'];它有效,但我怎么知道哪个数据来自哪个表?

$select_quote=mysql_query("SELECT authors.name, authors.id, authors.img, authors.slug, quotes.author_id, quotes.title, quotes.id, quotes.meta_keys, quotes.meta_description, quotes.slug, quotes.content
                           from quotes, authors
                           WHERE quotes.author_id = authors.id
                       ORDER BY RAND() LIMIT 1 ");

    while ($row=mysql_fetch_array($select_quote)) {

    $author_id = $row['authors.id'];
    $author_name = $row['authors.name'];
    $author_slug = $row['authors.slug'];

    echo" $author_slug";
    }

1 个答案:

答案 0 :(得分:0)

您可以在此字段中使用别名:

SELECT authors.name
     , authors.id
     , authors.img
     , authors.slug AS 'authors.slug'
     , quotes.author_id
     , quotes.title
     , quotes.id
     , quotes.meta_keys
     , quotes.meta_description
     , quotes.slug AS 'quotes.slug'
     , quotes.content
 FROM quotes, authors
 WHERE quotes.author_id = authors.id
 ORDER BY RAND() LIMIT 1 

所以你可以在php中访问检索到的数据,如:

 $author_slug = $row['authors.slug']
 $quotes_slug = $row['quotes.slug']