MYSQL组同样的ID?

时间:2014-09-10 20:03:51

标签: php mysql

我有以下2个表格:

表1:用户

   id   s_id   first_name   last_name
   ----------------------------------
   1     2     test          test
   2     2     hello         test
   3     2     now           hello
   4     1     john          smith

表2:部分

   id    section_name
  -------------------
   1     first
   2     my section
   3     other section

基于以上两个表,我想写一个MYSQL查询:

从用户表和GROUP THEM BY s_id(SAME s_id)中选择ALL,我该怎么做?

我想将所有s_id = 2 ALL组合在一起作为数组或对象,但由s_id控制?所以我会遍历s_ids并打印出名字和姓氏?

以下是输出示例:

$sections = array['my section'](array('first_name'=>'test' ,  'last_name'=>'test'),
                                array('first_name'=>'hello' ,  'last_name'=>'test'),
                                array('first_name'=>' now' ,  'last_name'=>'hello'))

感谢

3 个答案:

答案 0 :(得分:2)

简单地

SELECT * FROM `user` GROUP BY `s_id`

但是你的标题和内容都有不同的问题。

所以你在PHP中想要的是这样的:

while($row = your sql fetch)
{
    $array[$row['s_id']][] = array('first_name' => $row['first_name'], 'last_name' => $row['last_name']);
}

print_r($array);

答案 1 :(得分:0)

如果您需要s_id = 2以下的所有用户:

SELECT * FROM `user` where `s_id` = 2 # this will give 3 users

否则如果你与s_id分组,每个部分只会有一个用户,我认为你不想要那个

要显示全部,而不是必须运行查询:

SELECT user.*, section.section_name FROM `user`
INNER JOIN section ON section.id = user.s_id

在PHP中欺骗它:

$query = "
    SELECT 
        user.*, 
        section.section_name 
    FROM `user`
    INNER JOIN section 
        ON section.id = user.s_id
";

$result = mysqli_query($conn, $query);

$final_data = array();
while($data = mysqli_fetch_assoc($result))
{
    $final_data[$data['section_name']][] = $data;
}

print($final_data); // to see the result

答案 2 :(得分:0)

在php中查看mysqli_fetch_array函数。

您需要使用此php函数循环查询结果并将它们放入数组中,您不需要在sql中对任何内容进行分组,但仅限于:

select * from user order by s_id

在php循环中,您可以根据需要填充数组。

相关问题