我有一个表tbl_
问题。我想要这样的记录:
subject_id question_id
3 4,5
我的表格如下:
id question subject_id
1 a 1
2 b 1
3 c 2
4 d 3
5 e 3
6 f 3
我尝试过使用
SELECT subject_id, group_concat(id)
FROM tbl_qus_bank
WHERE subject_id=3
ORDER by RAND() LIMIT 2
但它不起作用。
答案 0 :(得分:1)
尝试子查询:
import
或者,您可以使用SELECT subject_id, group_concat(id)
FROM (SELECT qb.*
FROM tbl_qus_bank qb
WHERE subject_id = 3
ORDER by RAND() LIMIT 2
) qb
GROUP BY subject_id;
- 如果主题总数不是太大:
substring_index()
SELECT subject_id,
substring_index(group_concat(id) order by rand(), ',', 2)
FROM tbl_qus_bank
WHERE subject_id = 3;
和ORDER BY
适用于整个查询的结果。也就是说,在 LIMIT
已经生成结果之后,处理它们。