你好,我有两个表,在 InnoDB 引擎中有一个 PK---->FK 关系---->MySQL&PHP
第一个表'Properties'和第二个
之间的关系是one---->many'propertyimages' 表。第一个表中的每一行都是唯一的,但在第二个表中
第一个表的每一行在第二个表中都有很多行我如何**从中选择唯一行
这里的第一个表和第二个表中关于第一个表的所有信息是我的查询:
SELECT DISTINCT properties.PropertyName,
properties.PropertyStatus,
propertyimages.PropertyImageID,
propertyimages.ImagePath
FROM properties
INNER JOIN propertyimages
ON properties.PropertyImageID=propertyimages.PropertyImageID
AND propertyimages.PropertyImageID=8;
它给出结果:
PropertyName PropertyStatus Propertyid property Image Path Appartment For Lease 8 upload/hydrangeas.jpg Appartment For Lease 8 upload/jelsh.jpg Appartment For Lease 8 upload/penguins.jpg Appartment For Lease 8 upload/tulips.jpg
在这个结果中,PropertyName 和 PropertyStatus 是重复的,但我想要一个
独一无二,因为它存储在第一个表propertyName 和PropertyStatus
属于第一个表。Propertyid 和 PropertyImagepath 属于第二个表。
最佳答案
不幸的是,连接将为表 2 中找到的每个元素创建一条记录,并在第一个表中找到匹配的父元素 (id 8)。
您可以在第一个表字段上使用 GROUP BY id 8,但您可能无法获得所需的所有结果,因为它只会获取第一张图像。
你能否重组你的流程,以便在涉及图像(及其显示)时你可以只运行一个查询来获取与属性 8 相关的每张图像
您始终可以使用嵌套查询(假设您要在页面上显示图像以获得属性等)
$query1 = mysql_query("SELECT Propertyid, PropertyName, PropertyStatus FROM properties WHERE (search criteria)");
if (mysql_num_rows($query1) > 0) {
while ($q1Row = mysql_fetch_array($query1)) {
// Insert property specific data here before you display the images
echo $q1Row['PropertyName']."<br>\n";
echo $q1Row['PropertyStatus']."<br>\n";
$query2 = "SELECT PropertyImageID, ImagePath FROM propertyimages WHERE PropertyImageID='".$q1Row['Propertyid']."'"
if (mysql_num_rows($query2) > 0) {
while ($q2Row = mysql_fetch_array($query2)) {
// add code here to do whatever you want with the images
echo '<image src="'.$q2Row['ImagePath'].'"><br>\n';
}
}
}
}
}
它也有助于了解您的数据库结构..我想您会想要这样的东西
table 1 (properties)
PropertyID (Primary Key)
PropertyName
PropertyStatus
table 2 (propertyImages)
ImageID (Primary Key)
PropertyID (many to one reference to PropertyID in table 1)
ImagePath
我可能对 FK 方法有点遗忘,所以如果这里也有适合我的类(class),我很想听听您的意见。
关于php - MySQL 内连接表从唯一表中给出重复值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16129208/