如何在 MySQL 中返回具有相同列值的列?


為此,請使用 GROUP BY 子句。我們先建立一個表 -

mysql> create table DemoTable
   -> (
   -> StudentId int,
   -> StudentMarks int
   -> );
Query OK, 0 rows affected (4.71 sec)

使用 insert 命令在表中插入一些記錄 -

mysql> insert into DemoTable values(23,58);
Query OK, 1 row affected (0.70 sec)

mysql> insert into DemoTable values(25,89);
Query OK, 1 row affected (0.46 sec)

mysql> insert into DemoTable values(26,58);
Query OK, 1 row affected (1.13 sec)

mysql> insert into DemoTable values(28,98);
Query OK, 1 row affected (0.86 sec)

使用 select 語句顯示錶中的所有記錄 -

mysql> select *from DemoTable;

輸出

+-----------+--------------+
| StudentId | StudentMarks |
+-----------+--------------+
| 23        | 58           |
| 25        | 89           |
| 26        | 58           |
| 28        | 98           |
+-----------+--------------+
4 rows in set (0.00 sec)

這是在 MySQL 中返回具有相同列值的列的查詢 -

mysql> select StudentMarks from DemoTable
   -> group by StudentMarks
   -> having sum(StudentId=23) > 0 and
   -> sum(StudentId=26) > 0;

輸出

+--------------+
| StudentMarks |
+--------------+
| 58           |
+--------------+
1 row in set (0.00 sec)

更新於: 30-7-2019

226 檢視數

開啟你的 職業生涯

完成課程獲得認證

開始
廣告