我在从2个表中检索一些数据然后将输出显示到一个区域时遇到问题。
这是我有的检索代码
$select_users = "SELECT CarID, Model, Year, Price, ManuName FROM Vehicle, Manufacturer";
//run query
$result = mysql_query($select_users);
这是输出的代码
<?php
while ($user = mysql_fetch_array($result)){
$user_row = sprintf(
"<li><a href='select_veh.php?CarID=%d' class='mainnavstyle'>%s %s %s %s</a></li>",
$user['CarID'],
$user['ManuName'],
$user['Model'],
$user['Year'],
$user['Price']);
echo $user_row;
}
?>
我似乎无法获得“ManuName&#39;从另一张表中正确显示。 目前使用此代码即可获得重复结果:
honda Civic 2000 $15,000
honda Corolla 1991 $5,000
Toyota Civic 2000 $15,000
Toyota Corolla 1991 $5,000
而不仅仅是
Honda Civic 2000 $15,000
Toyota Corolla 1991 $5,000
非常感谢任何帮助 感谢
答案 0 :(得分:3)
您正在执行交叉连接,该交叉连接与一个表的每一行匹配,与另一个表的每一行匹配。这几乎可以肯定是你不想要的。您需要限制表格的连接方式,为此,您的表格车辆和制造商需要彼此相关,如下:
CREATE TABLE manufacturer (
id integer primary key auto_increment,
name varchar(255)
);
CREATE TABLE vehicle (
id integer primary key auto_increment,
name varchar(255),
year integer,
price double,
manufacturer_id integer not null,
FOREIGN KEY(manufacturer_id) REFERENCES manufacturer(id)
);
然后,您可以获得所需的信息:
SELECT m.name, v.name, v.year, v.price FROM vehicle v
INNER JOIN manufacturer m
ON v.manufacturer_id = m.id
您可以在此处查看此操作:http://sqlfiddle.com/#!9/5c1f2/1
答案 1 :(得分:0)
在vehicle
表格中我会得到制造商的外键,而不是查询:
SELECT Vehicle.CarID, Vehicle.Model, Vehicle.Year, Vehicle.Price, Vehicle.ManuName, Manufacturer.name
INNER JOIN Manufacturer ON(Vehicle.manufacturerId = Manufacturer.id)
FROM Vehicle
答案 2 :(得分:0)
你可以使用联合或联接
一起进行SQL查询或者,这也是你可以做的:
$sql1= "SELECT something FROM tbl WHERE column='".query."'";
$result1= $con->query($sql1);
if($result1->num_rows > 0){
while($row = $result->fetch_assoc()) {
$rowans = $row["row"];
$sql2= "SELECT * FROM tbl2 WHERE column2= '".something."'";
$gettingRows2= $con->query($sql);
if($gettingRows2->num_rows > 0){
while($anotherrow= $sql2->fetch_assoc()) {
$sql2Row= $anotherrow["row2"];
}
}
}
}
echo $rowans." ".$sql2Row;