我知道这可能真的很简单,但我试图找到一些类似的例子但失败了。
问题是我想从数据库中的图库中列出 8 张随机图像,按添加日期排序。我已经设法做到了这一点,但只有几个迭代查询变得非常慢。因此,如果有人会这么好心地教我将它们组合起来以获得更快的速度,我想 UNION 是要走的路吗?这是我的工作(但代码很慢)
<?php
$latestPictures = mysql_query("SELECT pictureID, addedDate FROM picture ORDER BY addedDate DESC LIMIT 8");
$latestConcerts = mysql_query("SELECT concertID, addedDate FROM concert WHERE pictureID is null ORDER BY addedDate DESC LIMIT 8");
// Add concerts and pictures to array
while($curFestival = mysql_fetch_object($latestPictures))
{
$array[$curFestival->addedDate] = "p" . $curFestival->pictureID;
}
while($curConcert = mysql_fetch_object($latestConcerts))
{
$array[$curConcert->addedDate] = "c" . $curConcert->concertID;
}
// Order array by key
krsort($array);
$latestArray = array_slice($array, 0, 8);
foreach($latestArray as $key => $value) {
$type = substr($value, 0, 1);
$ID = substr($value, 1);
// If type == picture
if($type == 'p')
{
$picturesPicturesID = mysql_query("SELECT concertID, name FROM photo WHERE concertID IN(SELECT concertID FROM concert WHERE pictureID = $ID) ORDER BY photoID");
// Get random picture
$curRandomPicture = rand(0, (mysql_num_rows($picturesPicturesID) - 1));
$curPictureConcertID = mysql_result($picturesPicturesID, $curRandomPicture, "concertID");
$curPictureName = mysql_result($picturesPicturesID, $curRandomPicture, "name");
$curPicture = mysql_fetch_object(mysql_query("SELECT c.URL, p.name FROM concert c, picture p WHERE p.pictureID = c.pictureID AND c.concertID = $curPictureConcertID"));
echo "Some image";
}
// If type == concert
if($type == 'c')
{
$concertPicturesID = mysql_query("SELECT concertID, name FROM photo WHERE concertID = $ID ORDER BY photoID");
// Get random picture
$curRandomPicture = rand(0, (mysql_num_rows($concertPicturesID) - 1));
$curPictureConcertID = mysql_result($concertPicturesID, $curRandomPicture, "concertID");
$curPictureName = mysql_result($concertPicturesID, $curRandomPicture, "name");
$curPicture = mysql_fetch_object(mysql_query("SELECT URL, name FROM concert WHERE concertID = $curPictureConcertID"));
echo "Some image";
}
}
?>
我意识到我忘了包括表格,它们是:
TABLE OF photo:
PKEY: photoID
FKEY: concertID
name
TABLE OF concert:
PKEY: concertID
FKEY: pictureID
name
URL
addedDate
TABLE OF picture
PKEY: pictureID
name
date
所以每个帖子都是 TABLE 照片和音乐会的一部分,但只有一些是图片的一部分,女巫有时只用于将不同的专辑组合在一起。当他们组合在一起时,我想要一个来自该分组 ID(图片)的随机名称帖子,如果他们是他们自己,则从那里随机名称帖子(音乐会)。