php mysql得到2个表值

时间:2015-06-24 11:56:10

标签: php mysql

现在我想查询数据以获取最新的获取代码。

现在我有2张桌子,

这是t1。

+--------------+--------------------------+----------------------+
|    id        |  name                    | description          |
+--------------+--------------------------+----------------------+
| 1            | GG                       | GG is good           |
| 2            | ABC DEFG                 | ABC DDDDD            |
| 3            | CCARD                    | Gooooo               |
+--------------+--------------------------+----------------------+

这是t2

+---------+------------+-------------------+------------------+
| id      | kaid       | code              | timestamp        |
+---------+------------+-------------------+------------------+
| 1       | 2          | ZZZZAAAAA         | 123456789        |
| 2       | 2          | AAAZZADWWW        | 123344444        |
| 3       | 1          | ASFASDFFFF        | 123333333        |
| 4       | 2          | HHHHHFDFG         | 123222222        |
| 5       | 1          | ASDASDADDDD       | 123111111        |
+---------+------------+-------------------+------------------+

我希望数据显示如下:

  

ORDER BY timestamp desc limit 5

+--------+------------+------------------+------------------
| id     | kaid       | name             | time             |
+--------+------------+------------------+------------------+
| 1      | 1          | GG               | 123111111        |
| 2      | 2          | ABC DEFG         | 123222222        |
| 3      | 1          | GG               | 123333333        |
| 4      | 2          | ABC DEFG         | 123344444        |
| 5      | 2          | ABC DEFG         | 123456789        |
+--------+------------+------------------+------------------+

现在我的代码是:

$querylist = mysql_query("SELECT * FROM t1 ORDER BY time desc limit 5");
while($rowlist = mysql_fetch_row($querylist)) {
    $idlist[] = $rowlist['id'];
    $user_list_latest[] = $rowlist;
}

如何在t1.id = t2.kaid?

时选择t2.name 非常感谢你!

4 个答案:

答案 0 :(得分:1)

SELECT t1.*,t2.name FROM t1,t2 where t1.id = t2.kaid  ORDER BY t1.time desc limit 5

你可以像这样使用

答案 1 :(得分:0)

您需要像{/ 1>一样使用join

select t1.name, t2.* from t2 
join t1 on t2.kaid = t1.id
order by time desc limit 5

答案 2 :(得分:0)

你必须加入这样的表,就像杰伊说停止使用mysql_ *函数:

$querylist = mysql_query("SELECT t1.*, t2.name FROM t1 INNER JOIN t2 ON t1.id=t2.kaid ORDER BY t1.time desc limit 5");
while($rowlist = mysql_fetch_row($querylist)) {
    $idlist[] = $rowlist['id'];
    $user_list_latest[] = $rowlist;
}

答案 3 :(得分:0)

试试这个

$querylist = mysql_query("SELECT t2.*, t1.name FROM t2
                          INNER JOIN t1
                          ON t1.id=t2.kaid
                          ORDER BY t2.time desc 
                          LIMIT 5");