-1

=) 我只是被这个问题困扰.. 如何根据类型对 mysql 中的行进行分组这里是我的示例输入和输出.. 可以说我的数据库中有这些

|Name | address |  type | 
a1    add1      t_spot
c2    add2      t_acc
e3    add3      t_res
b1    add1      t_spot
d2    add2      t_acc
f3    add3      t_res

我想按它们的类型对其进行分组并使用 php 将其放入选择框中让我们假设这将是预期的代码

<select name='all'>
<optgroup label="t_spot">
<option value=''>a1</option>
<option value=''>b1</option>
</optgroup>

<optgroup label="t_acc">
<option value=''>c1</option>
<option value=''>d1</option>
</optgroup>

<optgroup label="t_res">
<option value=''>e1</option>
<option value=''>f1</option>
</optgroup>
</select>

请帮助..非常感谢它将不胜感激..

4

2 回答 2

1

在您的查询中,ORDER BY type.

然后,在读取数据时,跟踪当前类型,当您看到更改时,您知道结束当前块并开始下一个块。伪代码:

select * from table order by type
cur_type=''
while(more rows)
    if (type != cur_type)
        if (cur_type != '')
            terminate optgroup block
        start new optgroup block
    write option
if (cur_type != '')
    terminate optgroup block
于 2012-02-08T06:44:51.903 回答
0

您需要根据类型使用 where 子句运行多个查询:

select * from table where type = 't_spot'
select * from table where type = 't_acc'
...

或者您需要查询所有行并根据类型在代码中按类型拆分它们。遍历结果并将它们放入用于填充 html 的单独列表中。ORDER BY 在这里可能会有所帮助,因此您可以在遍历结果时跟踪类型何时更改。

于 2012-02-08T06:45:56.720 回答