MySQL内部连接表给出来自唯一表的重复值


MySQL inner join table gives repetaed value from unique table

你好,我有两个表与一个PK---->FK关系在InnoDB引擎---->MySQL&PHP

第一个表'Properties'和第二个表 之间的关系是一个---->多个

'propertyimages'第一个表中的每一行都是唯一的,但在第二个表

第一个表的每一行在第二个表中有很多行,我怎么能**SELECT唯一的行

第一个表和所有关于第一个表的信息从第二个表,这是我的查询:

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属性图像路径出租公寓8个upload/hydrangeas.jpg出租公寓8个upload/jelsh.jpg公寓出租8个upload/penguins.jpg出租公寓8个upload/tulips.jpg之前

在这个结果中,PropertyNamePropertyStatus是重复的,但我想要一个

propertyNamePropertyStatus

属于第一个表。PropertyidPropertyImagepath属于第二个表

不幸的是,连接将为表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方法,所以如果这里对我也有一个教训,我很想听听你有什么输入

你离解决方案只有一步之遥,你只需要从第二个表中选择,然后选择第一个,这样你就会得到所有匹配的结果

SELECT DISTINCT properties.PropertyName, 
            properties.PropertyStatus, 
            propertyimages.PropertyImageID, 
            propertyimages.ImagePath 
FROM propertyimages 
   INNER JOIN properties  
     ON propertyimages.PropertyImageID = properties.PropertyImageID
     AND propertyimages.PropertyImageID=8;

您可以使用GROUP_CONCAT实现这一点。但我也认为,最好做两个查询。这没什么不对的。

SELECT DISTINCT properties.PropertyName, 
                properties.PropertyStatus, 
                propertyimages.PropertyImageID, 
                GROUP_CONCAT(propertyimages.ImagePath) 
FROM properties 
   INNER JOIN propertyimages 
      ON properties.PropertyImageID=propertyimages.PropertyImageID 
      AND propertyimages.PropertyImageID=8;
GROUP BY propertyimages.PropertyImageID