我有以下表格
表1
id name
1 joseph
2 john
3 george
4 lisa
5 michelle
表2
id city
1 New York
2 Los Angeles
3 Chicago
我需要获取table1中的所有数据并从table2中分配一个随机城市
这是我的查询
SELECT * FROM `table1`
LEFT JOIN (Select * From `table2` Order by Rand()) as temp
ON 1 = 1
问题是输出看起来像这样
joseph New York
joseph Chicago
joseph Los Angeles
john New York
john Chicago
john Los Angeles
george New York
george Chicago
george Los Angeles
等等
答案 0 :(得分:0)
在查询城市表时尝试使用LIMIT
SELECT * FROM `table1`
LEFT JOIN (Select * From `table2` Order by Rand() LIMIT 1) as temp
ON 1 = 1
答案 1 :(得分:0)
我会在select:
中使用子查询SELECT
id,
name,
(SELECT city FROM `table2` ORDER BY RAND() LIMIT 1) random_city
FROM `table1`