在mysql数据库中优化mysql查询

时间:2017-06-07 05:56:26

标签: mysql phpmyadmin

我想从最后一行属于rows类的class表中获取3 5,6 and 7个数据。

现在我使用3 sql次查询来获取数据:

 1. SELECT * from class where class_name = '5';

 2. SELECT * from class where class_name = '6';

 3. SELECT * from class where class_name = '7';

如何使用单个sql查询来检索3行数据而不是3个sql查询?

**class table structure:**

|id | class_name | student  |
|---| -----------| ---------| 
|1  |      5     | Student A|
|2  |      6     | Student B|
|3  |      4     | Student C|
|4  |      6     | Student D|
|5  |      7     | Student E|
|6  |      5     | Student F|
|7  |      4     | Student G|
|8  |      6     | Student H|
|9  |      5     | Student I|
|10 |      6     | Student J|
|11 |      7     | Student K|
|12 |      6     | Student L|
|13 |      8     | Student M|
|14 |      6     | Student N|
|15 |      8     | Student O|

需要的结果: 学生I,学生N和学生K

6 个答案:

答案 0 :(得分:1)

试试这个

SELECT * FROM class WHERE id IN (SELECT MAX(id) FROM class WHERE class_name in (5,6,7) GROUP BY class_name );

sqlfiddle

答案 1 :(得分:0)

select * from (select * from class order by id desc, class_name) x group by class_name

答案 2 :(得分:0)

SELECT * from (SELECT * from class ORDER BY id  DESC) t WHERE class_name in (5,6,7) GROUP BY class_name ORDER BY id DESC 

答案 3 :(得分:0)

使用子查询,因为GROUP BY不能与通配符一起使用。相反,您必须按所选的每列进行分组。

SELECT * FROM class
WHERE id IN (
    SELECT MAX(id) FROM class
    WHERE class_name IN (5, 6, 7) GROUP BY class_name ORDER BY id DESC
);

答案 4 :(得分:0)

SELECT * FROM class 
WHERE id IN (
    SELECT MAX(ID) 
    FROM dbo.class 
    WHERE class_name IN (5,6,7) 
    GROUP BY class_name )

这应该是技巧,经过测试,结果如下:

id          class_name student
----------- ---------- --------------------
1           5          A                   
2           6          B                   
3           4          C                   
4           6          D                   
5           7          E                   
6           5          F                   
7           4          G                   
8           6          H                   
9           5          I                   
10          6          J                   
11          7          K                   
12          6          L                   
13          8          M                   
14          6          N                   
15          8          O                   

(15 row(s) affected)

id          class_name student
----------- ---------- --------------------
9           5          I                   
11          7          K                   
14          6          N                   

(3 row(s) affected)

答案 5 :(得分:-1)

SELECT * from class where class_name =' 5'或class_name =' 6'或class_name =' 7'