嗨,我正在尝试将一些查询合并为一个,但我不确定如何解决这个问题。我知道还有数百万其他示例,但我不知道如何将它们翻译成我的查询。
这是数据库。首先是表名:,然后是主键和外键
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和addDate FROM gallery(每行1个galleryID不是8个相同),concertID和来自音乐会的URL(1个具有相同concertID的随机帖子),来自照片的名称(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;
我也尝试通过 JOIN 来执行此错误#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;