php - mysqli 获取记录

标签 php mysql mysqli mysqlimport picturegallery

这是关于一个帖子 Show three images from each user对于我遇到的相同问题,那里有很好的解决方案。

if ($stmt = $mysqli->prepare("SELECT p1.userID, p1.picture as pic1, p2.picture as pic2, p3.picture as pic3
FROM
  pictures p1 left join pictures p2
  on p1.userID=p2.userID and p1.picture<>p2.picture
  left join pictures p3
  on p1.userID=p3.userID and p1.picture<>p3.picture and p2.picture<>p3.picture
GROUP BY p1.userID
LIMIT ?,1")) {

    $stmt->bind_param("i", $first); 
    $stmt->execute();
    $stmt->bind_result($user, $pic1, $pic2, $pic3);
    $stmt->fetch();
    $stmt->close();
}
$mysqli->close();
?>
<div style="position:absolute; top:50px; left:100px; width:800px; text-align: center;">
  <img src="<?PHP echo (isset($pic1) ? $image_path.$pic1 : $no_image); ?>" width="176px" height="197px">
  <img src="<?PHP echo (isset($pic2) ? $image_path.$pic2 : $no_image); ?>" width="176px" height="197px">
  <img src="<?PHP echo (isset($pic3) ? $image_path.$pic3 : $no_image); ?>" width="176px" height="197px">
</div>

我想知道如何在此查询中也获得 pictureID?例如,如果我使用图片进行投票,那么我还必须获取 pictureID。

Supericy 帮助后的回答:(如果有人正在寻找相同的)

if ($stmt = $mysqli->prepare("SELECT p1.userID, p1.picture as pic1, p1.pictureID as pic1id, p2.picture as pic2, p2.pictureID as pic2id, p3.picture as pic3, p3.pictureID as pic3id
FROM
  pictures p1 left join pictures p2
  on p1.userID=p2.userID and p1.picture<>p2.picture
  left join pictures p3
  on p1.userID=p3.userID and p1.picture<>p3.picture and p2.picture<>p3.picture
GROUP BY p1.userID
LIMIT ?,1")) {

然后绑定(bind)

$stmt->bind_result($user, $pic1, $pic1id, $pic2, $pic2id, $pic3, $pic3id);

最佳答案

试试这个,

SELECT p1.userID,coalesce(p1.pictureID,p2.pictureID,p3.pictureID) pictureID, 
       coalesce(p1.picture,p2.picture,p3.picture) as pic
FROM
  pictures p1 left join pictures p2
  on p1.userID=p2.userID and p1.picture<>p2.picture
  left join pictures p3
  on p1.userID=p3.userID and p1.picture<>p3.picture and p2.picture<>p3.picture
GROUP BY p1.userID,pictureID,pic
LIMIT ?,1

关于php - mysqli 获取记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14026727/

相关文章:

PHP 排名和选择操作

php - 左连接 | ORDER BY 查询速度

php - 来自多个数据库表的Mysql联合

php - 通过 CMS 从表单存储内容时出现问题

mysql - Django 测试 django.db.utils.ProgrammingError : (1146, "Table ' DB.Table'不存在")

php - Mysqli_query无故返回FALSE

php - 表达式引擎,Expresso Store Payment Module

php - 使用 where 条件连接查询 codeigniter 返回所有行

mysql - 动态 MySql 查询每天返回 X 次结果

php - mysqli_multi_query() 重复获取 null