我有2张桌子
人物和图像
表人
+----+--------+----------+
| id | name | lastname |
+----+--------+----------+
| 1 | Jhon | Smith |
| 2 | George | Mutt |
| 3 | Peter | Law |
+----+--------+----------+
表格图片
+----+-----------+------------+
| id | id_people | img |
+----+-----------+------------+
| 1 | 1 | demo04.jpg |
| 2 | 2 | test1.jpg |
| 3 | 2 | orange.jpg |
| 4 | 2 | flow.png |
| 5 | 3 | darth.png |
| 6 | 3 | green.png |
+----+-----------+------------+
我需要让所有人随机拥有一张图片。
例如,结果很好。
+----------------------------+
1 | Jhon | Smith | demo04.jpg
2 | George | Mutt | orange.jpg
3 | Peter | Law | green.png
+----------------------------+
或其他结果。
+----------------------------+
1 | Jhon | Smith | demo04.jpg
2 | George | Mutt | test1.jpg
3 | Peter | Law | darth.png
+----------------------------+
I used this sql query
SELECT *
FROM `people` p
INNER JOIN (SELECT *
FROM images
ORDER BY Rand()
LIMIT 1)i
ON i.id_people = p.id
WHERE 1
但只返回一行。
+----+--------+----------+----+-----------+------------+
| id | name | lastname | id | id_people | img |
+----+--------+----------+----+-----------+------------+
| 2 | George | Mutt | 3 | 2 | orange.jpg |
+----+--------+----------+----+-----------+------------+
出现了什么错误?
答案 0 :(得分:1)
在这种情况下,使用相关子查询而不是join
:
SELECT p.*,
(select i.img
from images i
where i.id_people = p.id
order by rand()
limit 1
) as img
FROM `people` p ;