日期:2014-05-16  浏览次数:20421 次

怎样同时查询多个数据表
有3个表(jtrb1,jtrb2,jtrb3),每个表都有几十万行记录,且每个表字段名称都一样(id,name,price,intime,outtime
怎样同时查询3个表里的内容?
比如我要在3个表里同时查字段name为“上衣”价格price小于“300”的记录。
求贴个PHP代码,单个表查询会做,多个表的就搞不动了。
另外:多表查询能不能用
while($row = mysql_fetch_array($result))

来输出内容?
最主要的还是贴个代码啊。谢谢啦!!
------解决方案--------------------
引用:
Quote: 引用:

单个

$result1 = mysql_query("select * from jtrb1 where name='上衣' and price < 300");
$row1 = mysql_fetch_array($result1);

$result2 = mysql_query("select * from jtrb2 where name='上衣' and price < 300");
$row2 = mysql_fetch_array($result1);

$result3 = mysql_query("select * from jtrb3 where name='上衣' and price < 300");
$row3 = mysql_fetch_array($result3);



组合

select * from jtrb1,jtrb2,jtrb3 
where jtrb1.name='上衣' and jtrb1.price < 300
and   jtrb2.name='上衣' and jtrb2.price < 300
and   jtrb3.name='上衣' and jtrb3.price < 300

组合这里,在数据库里查询,3个数据库里都有一条相同的记录,但它只列出一条,我想把三条都列出来,这里要怎么写?
还有
<?php 
$con = mysql_connect("localhost","root","");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db("test", $con);
$query="SELECT * FROM jtrb1,jtrb2,jtrb3 WHERE jtrb1.name='上衣' and jtrb2.name='上衣' and jtrb3.name='上衣'";
$result= mysql_query($query,$con)or die(mysql_error());
$row= mysql_fetch_array($result);
while($row)
  {
  echo $row['jtrb1.Name']."<br>";
  //下面省略
  }
  mysql_close();
?>

我这样子写输出空白。请大神指点。



把数组打印出来。。用foreach试一试。
------解决方案--------------------
UNION试试
------解决方案--------------------

select * from (
select * from jtrb1 where jtrb1.name='上衣' and jtrb1.price < 300 
union all
select * from jtrb2 where jtrb2.name='上衣' and jtrb2.price < 300 
union all 
select * from jtrb3 where jtrb3.name='上衣' and jtrb3.price < 300
) as t