PHP& Mysql无法使用UNION获取表的名称

时间:2014-06-22 09:32:06

标签: php mysql sql

if($result = mysql_query(
"SELECT `condition` FROM `table1` WHERE `id` = '1')
 UNION ALL
SELECT `condition` FROM `table2` WHERE `id` = '1')
 UNION ALL
SELECT `condition` FROM `table3` WHERE `id` = '1')"
){ 
      $num = mysql_num_rows($result);
      for($i = 0;  $i < $num; $i++){     
        $table = mysql_field_table($result, $i);
        echo  $table.' cond: '.mysql_result($result, $i, 'condition').', ';
      }
}

这里我可以获得查询结果(条件),但我也想得到表的名称,为了知道结果属于哪个表,我试过了:mysql_field_table($ result,$ i),但它不会返回任何东西。 所以请帮我拿到桌子的名字,提前谢谢你。

2 个答案:

答案 0 :(得分:2)

您有一组计算的列,因此您无法追溯到源表。您需要自己添加信息:

SELECT `condition`, 'table1' AS source
FROM `table1`
WHERE `id` = '1'

UNION ALL

SELECT `condition`, 'table2'
FROM `table2`
WHERE `id` = '1'

UNION ALL

SELECT `condition`, 'table3'
FROM `table3`
WHERE `id` = '1'

答案 1 :(得分:0)

使用此

  SELECT `condition`, '1' tablnumber FROM `table1` WHERE `id` = '1'
  UNION ALL
  SELECT `condition`,'2' FROM `table2` WHERE `id` = '1'
  UNION ALL
  SELECT `condition`,'3' FROM `table3` WHERE `id` = '1'

demo here