2014-09-10 85 views
-1

我有以下2个表:MYSQL Group通过相同的ID?

表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查询到:

SELECT ALL f rom用户表和GROUP THEM BY s_id(SAME s_id),我怎么能这样做?

我想获得所有的s_id = 2所有组合在一起作为数组或对象,但由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')) 

感谢

+0

你能展示你想要获得的输出的例子吗? – Mureinik 2014-09-10 20:06:23

+0

当然我会更新这个问题 – user3150060 2014-09-10 20:06:41

回答

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 
+0

但我不想指定一个特定的s_id =#,我想抓住所有获得相同数字的所有s_dis = 2和s_id = 1在一起等.. – user3150060 2014-09-10 20:18:33

+0

好的,我已经更新了 – 2014-09-10 20:23:11

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); 
+0

我认为'WHERE s_id = 2'应该被添加。 OP:*“我想将所有s_id = 2'都分组在一起” - 但是,我可能是错的。 – 2014-09-10 20:10:35

+1

我正在编辑这个答案:) – 2014-09-10 20:11:10

+0

那么这个输出是什么? – user3150060 2014-09-10 20:11:56

0

看看在PHP mysqli_fetch_array功能。

您需要周期,这个PHP函数查询结果,并把它们放在一个数组,你并不需要在SQL类的话,但仅限于:

select * from user order by s_id

在PHP周期可以根据需要填充阵列。