php - 由于过于严格的 WHERE 语句而缺少行

标签 php mysql

在下面的示例代码中,我们试图将我们的问题最小化为一个简化的测试用例。

我们有 3 个表:users、images 和 ratings。

1:我们要打印‘ratings’表中的所有条目。

2:在“图片”表中,可以有多个图片由同一用户上传到网站的不同部分,例如“user_profile_picture”或“user_cover_photo”。

3:打印评分时,如果用户上传了个人资料图片(section = ‘profile_picture’),我们希望从‘images’表中获取条目。

对于没有上传个人资料照片的用户,示例代码中查询中的 WHERE 语句失败。

如果 section = profile_picture ...,我们如何确保打印所有条目,以及只抓取与用户相关的图像?

CREATE TABLE `test_ratings` (
  `id` int(4) UNSIGNED NOT NULL AUTO_INCREMENT,
  `user_id` int(4) UNSIGNED NOT NULL,
  `rating` enum('1','2','3','4','5') DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
    
INSERT INTO `test_ratings` (`id`, `user_id`, `rating`) VALUES
    (2, 2, '4'),
    (1, 1, '5');
    
CREATE TABLE `test_users` (
    `id` int(4) UNSIGNED NOT NULL AUTO_INCREMENT,
    `username` varchar(30) NOT NULL,
    PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
    
INSERT INTO `test_users` (`id`, `username`) VALUES
    (1, 'Test person 1'),
    (2, 'Test person 2');
    
CREATE TABLE `test_users_images` (
    `id` int(4) UNSIGNED NOT NULL AUTO_INCREMENT,
    `filename` varchar(80) NOT NULL,
    `section` enum('user_cover_photo','user_profile_picture') DEFAULT NULL,
    `user_id` int(4) UNSIGNED DEFAULT NULL,
    PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
    
INSERT INTO `test_users_images` (`id`, `filename`, `section`, `user_id`) VALUES
    (1, 'rtfos.jpg', 'user_profile_picture', 2),
    (2, 'exer8.jpg', 'user_cover_photo', 2);
    
<?php
   $mysqli = new mysqli("localhost", "root", "", "website");

   $result = $mysqli->query('SELECT image.filename, user.username, ratings.rating
      FROM test_ratings ratings
      INNER JOIN test_users user ON user.id = ratings.user_id
      INNER JOIN test_users_images image ON image.user_id = user.id
      WHERE image.section = \'user_profile_picture\'');
  
   while ($row = $result->fetch_object()) {
      echo '<p>' . $row->username . ' - ' . $row->filename . '</p>';
   }
?>

最佳答案

如前所述,从用户表开始并左连接到它。在相应连接的 ON 子句中包含图像部分过滤器。

SELECT image.filename,
       user.username,
       ratings.rating
       FROM test_users user
            LEFT JOIN test_users_images image
                      ON image.user_id = user.id
                         AND image.section = 'user_profile_picture'
            LEFT JOIN test_ratings ratings
                      ON user.id = ratings.user_id;

db<>fiddle

附言:这是一个WHERE 子句,而不是一个语句。

关于php - 由于过于严格的 WHERE 语句而缺少行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68787710/

相关文章:

python - 我需要将原始 MySQL 查询转换为 Django ORM 查询

php - 向大型 SQL 查询添加检查

php - 反转输出顺序

mysql - MariaDB Galera 集群服务器以 100% CPU 运行并且负载不断上升

mysql - 为 00.0 指定 float 大小

mysql - Node.js 服务器中 mysql 数据库的要求

c# - 如何使用c#将数据添加到mysql中的指定列

php - 获取组合框中的数据

php - 根据键=>值对对数组进行排序

php - Drupal 8.5.1 升级错误 - 在哪里查找故障排除?