怎樣同時查詢多個資料表
有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個資料庫裡都有一條相同的記錄,但它只列出一條,我想把三條都列出來,這裡要怎麼寫?
還有
$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']."
";
//下面省略
}
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