[英]PHP and MySQL -> displaying data
I have successfully accomplished my first step ( link to my G+ post , but you don't have to read it. Everything is here). 我已经成功地完成了第一步( 链接到我的G +帖子 ,但是您不必阅读它。一切都在这里)。 Now there are some complications.
现在有一些并发症。 This is demo table:
这是演示表:
ID | userid | Age | Name --------------------------- 1 | 1 | 30 | John 2 | 1 | 31 | Mike 3 | 1 | 30 | Whoever 4 | 2 | 32 | Jack 5 | 2 | 31 | Alice 6 | 3 | 30 | Kurt
I would like to display only rows with userid = 1
+ persons with the same age have to be in the same row: 我只想显示
userid = 1
+具有相同年龄的人必须在同一行中的行:
userid | Age | Name --------------------------------- 1 (hidden) | 30 | John, Whoever 1 (hidden) | 31 | Mike
In my database I'm using subject
and grade
instead of age
and name
. 在我的数据库中,我使用的是
subject
和grade
而不是age
和name
。 This is how my MySQL query looks right now: 这是我的MySQL查询现在的样子:
SELECT
p.subject as 'subject'
GROUP_CONCAT(grade) as grades
FROM grades p
GROUP BY p.subject
This displays data for every userid
. 这将显示每个
userid
数据。 Userid
isn't always 1 so I can't just say if($userid == 1){/*code*/}else{/*code*/}
or anything similar. Userid
并不总是1,所以我不能只说if($userid == 1){/*code*/}else{/*code*/}
或类似的东西。
How can I accomplish this? 我该怎么做?
Some PHP code I'm using to display data: 我用来显示数据的一些PHP代码:
<?php
$result = $dbc->query("
SELECT
p.subject as 'subject',
id, finished, date,
GROUP_CONCAT(grade) as names
FROM grades p
GROUP BY p.subject
");
?>
<table>
<tr>
<th>Subject</th>
<th>Grade</th>
</tr>
<?php while($row = $result->fetch_assoc()){
$names = split(",",$row["names"]);
?>
<tr>
<td><?php echo $row["subject"] ?> </td>
<td><?php foreach( $names as $name){echo $name . ' ' ; } ?>
</tr>
<?php } ?>
</table>?
Ok I have been playing around with this and I have got it 好吧,我一直在玩这个,我知道了
Looks like you want to group by both user id and age so that you can perform aggregates on data which both have a specific userid and age. 看起来您想按用户ID和年龄进行分组,以便可以对具有特定用户ID和年龄的数据进行汇总。
I have included the code to create the table and insert the data incase anyone reading the question wanted to have a quick play. 我已经包含了创建表和插入数据的代码,以防万一有人阅读该问题时希望快速播放。
create table grades
(
id int(2),
userid int(2),
age int(2),
name varchar(20),
)
insert into grades values
(1,1,30,'John'),
(2,1,31,'Mike'),
(3,1,30,'Whoever'),
(4,2,32,'Jack'),
(5,2,31,'Alice'),
(6,3,30,'Kurt');
SELECT
userid, age, GROUP_CONCAT(name)
FROM grades
GROUP BY userid, age
http://sqlfiddle.com/#!9/7d9ac/3 http://sqlfiddle.com/#!9/7d9ac/3
SELECT Age, GROUP_CONCAT(Name)
FROM grades
WHERE userid=1
GROUP BY Age
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.