我对sql和php有点新意,所以我需要一些帮助。我创建了两个表,我想建立一个“一对多关系”,但我无法弄清楚如何通过php文件提供数据。这是一些代码:
CREATE TABLE `details` (
`details_id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(30) NOT NULL,
`latitude` double NOT NULL,
`longitude` double NOT NULL,
`mytext` varchar(60) NOT NULL,
`description` varchar(600) NOT NULL,
`city_details` int(11) NOT NULL,
PRIMARY KEY (`details_id`),
FOREIGN KEY (`city_details`) REFERENCES city(`city_id`)
on update cascade
);
CREATE TABLE `city` (
`city_id` int(11) NOT NULL AUTO_INCREMENT,
`cityName` varchar(30) NOT NULL,
PRIMARY KEY (`city_id`)
);
所以我想写一个cityName,然后能够为城市的各个地方提供一些数据。我怎样才能创建一个php文件,这样我只需要给出城市名称(到表城市),然后为城市内的多个位置写东西(到表格详细信息)。
答案 0 :(得分:1)
$sql="SELECT * FROM `details` as d INNER JOIN `city` as c ON d.city_details=c.city_id;";
如果您想查找城市名称,可以使用此
$sql="SELECT * FROM `details` as d INNER JOIN `city` as c ON d.city_details=c.city_id WHERE c.cityName='The name you're looking for'";
然后从表中获取每个使用此代码
while($row=mysql_fetch_assoc(mysql_query($sql))){
echo $row['name']; //for name
echo $row['mytext']; //etc.
}
了解更多信息,请参阅 http://dev.mysql.com/doc/refman/5.1/en/join.html 和 http://php.net/manual/en/function.mysql-fetch-assoc.php