【发布时间】:2021-09-17 00:39:13
【问题描述】:
我有一个 'imageposts' 表,我正在使用一个 'users' 表创建一个 left join,这样如果有一个图像帖子,它就会为完成该相关图像帖子的用户获取数据。
这两个表是链接的,因为“imageposts”表中的“user_id”列是“users”表中“id”列的外键。
虽然下面的代码有效,但当有图片发布时,它当前会使用 MySQL 查询(总共 12 列)从“用户”表中提取所有字段,而我只使用其中 2 列(名字和姓氏),这似乎过度/不是最好的解决方案?
我正在尝试解决如何只从“用户”中提取两个字段(名字和姓氏),同时从“图像帖子”表中选择所有内容?
非常感谢任何帮助。
<?php
$stmt = $connection->query("SELECT * FROM imageposts left join users on imageposts.user_id = users.id");
while ($row = $stmt->fetch()) {
// from imageposts table (every column in the table is used)
$db_image_id = htmlspecialchars($row['image_id']);
$db_image_title = htmlspecialchars($row['image_title']);
$db_image_tags = htmlspecialchars($row['image_tags']);
$db_image_filename = htmlspecialchars($row['filename']);
$db_ext = htmlspecialchars($row['file_extension']);
$db_processed= htmlspecialchars($row['user_processed']);
$db_username = htmlspecialchars($row['username']);
$db_profile_image_filename = htmlspecialchars($row['profile_image']);
// from users table (only 2 of the 12 columns returned in the query are used)
$db_firstname = htmlspecialchars($row['firstname']);
$db_lastname = htmlspecialchars($row['lastname']);
?>
<figure>
<!-- HMTL output goes here including the above variables -->
</figure>
<?php } ?>
【问题讨论】:
-
只需列出
imagepost中的所有列,加上SELECT中users表中的firstname和lastname。这也适用SELECT imagepost.*, users.firstname, users.lastname FROM ...,但最好指定所有你想要的列
标签: php mysql database left-join