使用php显示来自多个mysql表的结果

时间:2013-10-24 11:38:51

标签: php mysql

我有多个具有相同结构的mysql表。我试图用一个查询显示所有表的所有结果。我现在在网上搜索了几个小时,这就是我想出来的。

    $videos_query = mysql_query("SELECT 
                    table1.title,
                    table1.url,
                    table1.image,
                    table2.title,
                    table2.url,
                    table2.image,
                    table3.title,
                    table3.url,
                    table3.image
                 FROM
                    table1
                 INNER JOIN table2 ON table1.url = table2.url
                 INNER JOIN table3 ON table1.url = table3.url");
while($video_info = mysql_fetch_array($videos_query)){

然而,在PHP中使用上面的代码我得到错误“警告:mysql_fetch_array()期望参数1是资源,布尔给定”

3 个答案:

答案 0 :(得分:1)

您的SQL查询中有错误 - table1必须为table2

$videos_query = mysql_query("SELECT 
                    table1.title,
                    table1.url,
                    table1.image,
                    table2.title,
                    table2.url,
                    table2.image,
                    table3.title,
                    table3.url,
                    table3.image
                 FROM
                    table1
                 INNER JOIN table2 ON table1.url = table2.url
                 INNER JOIN table3 ON table1.url = table3.url");

if (mysql_num_rows($videos_query) > 0) {
    while ($video_info = mysql_fetch_array($videos_query)) {
        // process your data here
    }
}

如果你想做工会选择:

$videos_query = mysql_query("
  SELECT title, url, image
  FROM table1
  UNION
  SELECT title, url, image
  FROM table2
  UNION
  SELECT title, url, image
  FROM table3
");

if (mysql_num_rows($videos_query) > 0) {
    while ($video_info = mysql_fetch_array($videos_query)) {
        // process your data here
    }
}

此外,您可能希望按某些列进行排序 - 然后添加ORDER BY + column_name。

答案 1 :(得分:1)

更改

 INNER JOIN table2 ON table1.url = table1.url

INNER JOIN table2 ON table1.url = table2.url

答案 2 :(得分:0)

在检查ON时,您正在比较不正确的table1.url = table1.url

这是正确的代码:

$videos_query = mysql_query("SELECT 
                table1.title,
                table1.url,
                table1.image,
                table2.title,
                table2.url,
                table2.image,
                table3.title,
                table3.url,
                table3.image
             FROM
                table1
             INNER JOIN table2 ON table1.url = table2.url
             INNER JOIN table3 ON table1.url = table3.url");
while($video_info = mysql_fetch_array($videos_query)){