您好我正在尝试将一些查询合并为一个,但我不确定如何解决这个问题。我知道还有数以百万计的其他例子,但我无法弄清楚如何将它们翻译成我的查询。
这是数据库。首先是表名:,然后是主键和外键
gallery:
galleryID
name
addedDate
concert:
concertID
galleryID
name
URL
addedDate
photo:
photoID
concertID
name
这是我的查询,它在随机情况下在URL上返回NULL。我想这是因为应该同时选择concertID和URL。但是不允许SELECT concertID, URL FROM concert WHERE galleryID = g.galleryID ORDER BY RAND() LIMIT 1
所以如何解决这个问题?
我在第一个查询中选择的内容是正确的,除了在URL上获取NULL。所以我需要选择的是galleryID和addedDate FROM gallery(每行1个galleryID,而不是相同的8个),concertID和来自Concert的URL(1个随机帖子,具有相同的concertID),名称FROM照片(1个具有相同concertID的随机帖子)。给我这些结果:
11 2012-07-31 15:44:35 90 Picture\Path11 SomePicture28.jpg
36 2012-07-31 14:31:36 208 Picture\Path36 SomePicture11.jpg
09 2012-07-30 15:28:02 33 Picture\Path09 SomePicture69.jpg
SELECT galleryID, addedDate,
(SELECT concertID
FROM concert
WHERE galleryID = g.galleryID
ORDER BY RAND() LIMIT 1) AS curID,
(SELECT URL
FROM concert
WHERE concertID = curID) AS URL,
(SELECT p.name
FROM photo p, concert c
WHERE p.concertID = curID AND c.galleryID = g.galleryID
ORDER BY RAND() LIMIT 1) AS photoName
FROM gallery g ORDER BY addedDate DESC LIMIT 8;
我还尝试使用此错误#1054 - Unknown column 'p.concertID' in 'where clause'
SELECT galleryID, addedDate, c.concertID, c.URL, p.name
FROM (SELECT concertID, URL,
(SELECT name
FROM photo
WHERE p.concertID = curID.concertID
ORDER BY RAND() LIMIT 1) AS photoName
FROM concert
WHERE c.galleryID = curID.galleryID
ORDER BY RAND() LIMIT 1) curID
LEFT JOIN concert c ON curID.galleryID = c.galleryID
LEFT JOIN photo p ON p.name = curID.photoName
ORDER BY addedDate DESC LIMIT 8;
答案 0 :(得分:0)
在查询中,“FROM”子句中有相关的子查询。事情变得越来越混乱。
看起来你正试图让一张与音乐会相关的照片(在画廊中)。您可以通过将相关子查询移动到“SELECT”子句来完成此操作:
SELECT galleryID, addedDate, c.concertID, c.URL,
(select name
from photo p
where p.concertID = c.concertId
order by rand()
limit 1
) photoname
FROM concert c left join
gallery g
ON g.galleryID = c.galleryID
ORDER BY addedDate DESC
LIMIT 8;
要从8个不同的画廊中获取8张照片,请尝试以下操作:
SELECT galleryID, addedDate, c.concertID, c.URL,
(select name
from photo p
where p.concertID = c.concertId
order by rand()
limit 1
) photoname
FROM (select g.*
from gallery g
order by rand()
limit 8
) g join
concert c
ON g.galleryID = c.galleryID
where c.concert_id =
(select csub.concert_id
from concert csub
where csub.galleryID = g.galleryID
order by rand()
limit 1
)
ORDER BY addedDate DESC
答案 1 :(得分:0)
我在SQL中看不出为什么你为URL获取null,他们都有值。
我以其他格式重新发送您的查询,它与您已经执行的操作相似
SELECT R.*, c.URL, (SELECT p.Name FROM Photo p WHERE p.ConcertID = R.CurID ORDER BY RAND() LIMIT 1) AS PhotoName
FROM
(SELECT GalleryID, AddedDate,(SELECT ConcertID FROM Concert c WHERE c.GalleryID = g.GalleryID ORDER BY RAND() LIMIT 1) AS CurID
FROM Gallery g
ORDER BY AddedDate DESC LIMIT 8) AS R
JOIN Concert c ON R.CurID = c.ConcertID