假设我有下面两个表示例
第一个表
CREATE TABLE `student` (
`student_id` int(11) NOT NULL,
`student_name` varchar(255) NOT NULL,
`class_id` int(11) NOT NULL,
);
示例数据
1,James,1
2,Dorris,1
3,Maximus,2
4,Paul,1
第二个表
CREATE TABLE `class` (
`class_id` int(11) NOT NULL,
`class_name` varchar(255) NOT NULL,
);
示例数据
1, Red
2, Blue
对于每个学生记录,我想提供一些序列号,例如
类(class)名称/类(class)学生总数/记录编号
詹姆斯的示例 - 红色/3/1 多丽丝 - 红色/3/2 保罗-红/3/3
马克西姆斯 - 蓝色/1/1
到目前为止我尝试过的
$result="SELECT * FROM class where class_id='1' ";
$result=mysqli_query($connection,$result);
$row=mysqli_fetch_array($result);
$class_name=$row['class_name'];
$getstudent="SELECT * FROM student where class_id='1' and student_id='1'";
$result=mysqli_query($connection,$getstudent);
$totalstudent=mysqli_num_rows($getstudent);
echo "$class_name/$totalstudent/";
我如何获取记录编号,我认为在查询中使用计数..我需要帮助
最佳答案
连接两个表并创建新列,如下所示:
SELECT
s.*,
concat(
c.class_name, '/',
(SELECT count(*) FROM student WHERE class_id = s.class_id), '/',
(SELECT count(*) FROM student WHERE class_id = s.class_id AND student_id < s.student_id) + 1
) serial
FROM student s INNER JOIN class c
ON c.class_id = s.class_id
请参阅demo .
结果:
| student_id | student_name | class_id | serial |
| ---------- | ------------ | -------- | -------- |
| 1 | James | 1 | Red/3/1 |
| 2 | Dorris | 1 | Red/3/2 |
| 3 | Maximus | 2 | Blue/1/1 |
| 4 | Paul | 1 | Red/3/3 |
关于mysql - 统计并显示每条记录数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55750833/