我有一些表还原用户文章。表格的结构就像......
id | uid | imgae |
1 | 1 | 1.jpg |
2 | 1 | |
3 | 2 | 2.jpg |
4 | 3 | 3.jpg |
5 | 3 | |
6 | 3 | 4.jpg |
7 | 4 | |
...
然后我想得到10个结果女巫image!=''
(select * from my_table where image!='' order by rand() limit 1)
UNION
(select * from my_table where image!='' order by rand() limit 1)
UNION
(select * from my_table where image!='' order by rand() limit 1)
UNION
(select * from my_table where image!='' order by rand() limit 1)
UNION
(select * from my_table where image!='' order by rand() limit 1)
UNION
(select * from my_table where image!='' order by rand() limit 1)
UNION
(select * from my_table where image!='' order by rand() limit 1)
UNION
(select * from my_table where image!='' order by rand() limit 1)
UNION
(select * from my_table where image!='' order by rand() limit 1)
UNION
(select * from my_table where image!='' order by rand() limit 1)
以及如何进一步查询。结果是10个不同的uid
(a.uid!=b.uid
)?代码太长了...任何简单的方法?感谢。
答案 0 :(得分:1)
更改限制并按以下方式添加组:
select * from my_table where image!='' order by rand() group by uid limit 10
答案 1 :(得分:1)
你为什么不这样做:
SELECT * FROM my_table
WHERE image != ''
ORDER BY RAND()
LIMIT 10
如果你只想要DISTINCT uid
,你可以这样做:
SELECT DISTINCT uid, id, image FROM my_table
WHERE image != ''
ORDER BY RAND()
LIMIT 10
(MySQL人刷新我的记忆 - 当你选择DISTINCT uid
时,MySQL会选择相应的id,图像行还是更像GROUP BY
,你不一定得到相应的行?)< / p>