php - MySQL 内连接表从唯一表中给出重复值

标签 php mysql

你好,我有两个表,在 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

在这个结果中,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 方法有点遗忘,所以如果这里也有适合我的类(class),我很想听听您的意见。

关于php - MySQL 内连接表从唯一表中给出重复值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16129208/

相关文章:

php - SSL 的 fsockopen 错误

javascript - 使用 JavaScript/php 的下一个上一个函数

php - 将参数添加到覆盖方法 E_STRICT 观察

mysql - "CONCAT"生成的列未显示在数据库表中

mysql - 需要精确的 MYSQL 查询帮助

php - 使用 PHP 在 Mysql 中存储和检索 JPG

php - 我们可以知道是否正在使用YouTube API进行流式传输吗?

php - 删除从数据库检索的 TIME 函数前面的零?

MySQL - 如何查询多值字段以匹配另一个表的主键?

php - 即使在成功操作后 Apigility 也会返回错误