(SELECT * FROM table1
INNER JOIN table2
ON table1.id = table2.id)
AS t1
JOIN (SELECT ROUND(RAND() * (SELECT MAX(table1.id) FROM table1)) AS id)
AS t2
WHERE t1.id >= t2.id
LIMIT 1)
我尝试使用RAND()
max(id)
来获取随机的mysql结果,但得到#1064
错误。
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AS t1 JOIN (SELECT ROUND(RAND() * (SELECT MAX(table1.id) FROM table1))' at line 1
问题出在哪里?感谢。
答案 0 :(得分:3)
(假设此代码段是整个查询)
可能是错的,但你的陈述没有SELECT ......总之它看起来像这样:
t1 JOIN t2 WHERE ...
没有SELECT FROM FROM t1 JOIN t2 WHERE ...
我不确定自己是否清楚......
附录:
不确定您要尝试实现的目标,但此代码会在您的表中返回随机ID(查询的变体),因此您可以使用它。也许有点乱,但我又不知道你想要实现什么:)。
SELECT * FROM
(SELECT table1.id as id1
FROM table1
INNER JOIN table2
ON table1.id = table2.id) as t1
JOIN (
(SELECT ROUND(RAND() * (SELECT MAX(table1.id) FROM table1)) AS id2)
AS t2 )
WHERE t1.id1 >= t2.id2
LIMIT 1
您可以选择id1或id2而不是*,具体取决于您的目标......
答案 1 :(得分:0)
(假设此代码段是更大查询的一部分)
问题是这个子查询:
(SELECT * FROM table1
INNER JOIN table2
ON table1.id = table2.id)
AS t1
单独运行:
SELECT * FROM table1
INNER JOIN table2
ON table1.id = table2.id ;
不会出错,但会显示/返回至少2个具有相同名称的列(id
)。当您尝试将其作为子查询包含在更大的查询中时,这会导致冲突。