A有一张表:
id | name | idparent | info 1 | AA | | x 2 | BB | | 3 | CC | | x 4 | DD | 1 | 5 | EE | 1 | 6 | FF | 2 | 7 | GG | 2 | 8 | HH | 3 | 8 | HH | 4
我想做的事情是用mySQL / PHP做的:
SELECT id FROM table WHERE info LIKE 'x'
和PHP
for i in each id result of the first request : SELECT id, name FROM table where idparent = i ORDER BY RAND() LIMIT 1; endFor例如,结果可能是:
4 |DD 8 |HH
由于RAND(),结果也是如此:
5 |EE 8 |HH
但它不是那么漂亮,是否有可能只在一个请求中执行此操作?
我尝试了几个想法,但没有成功,我不在这里列举,为了不污染理解我的主题:))
提前感谢您的回答
答案 0 :(得分:5)
这是一个使用sub-queries
的解决方案,它只对MySQL有效,因为MySQL的GROUP BY
行为是SQL标准的扩展。
GROUP BY
的MySQL解决方案:SELECT t.id, t.name
FROM (
SELECT id, name, idparent
FROM table
where idparent IN (SELECT id FROM table WHERE info LIKE 'x')
ORDER BY RAND()
) t
GROUP BY t.idparent;
通过group rank
user variable
分配非MySQL的解决方案:
SELECT *
FROM (
SELECT
id, name, idparent,
IF(idparent = @last_idparent, @grp_rank := @grp_rank + 1, @grp_rank := 1) as grp_rank
FROM table CROSS JOIN (SELECT @grp_rank := 1, @last_idparent := NULL) param
where idparent IN (SELECT id FROM table WHERE info LIKE 'x')
ORDER BY RAND()
) t
WHERE t.grp_rank = 1;
答案 1 :(得分:1)
试试这个:
SELECT id, name FROM table natural join (SELECT id as idparent FROM table WHERE info LIKE 'x') as T ORDER BY RAND() LIMIT 1;
我希望这能解决问题。