mysql - 在 SQL 中编写和执行子查询

标签 mysql

我有这张表:

Event_id    place   money
101         1       120
101         2       60
101         3       30
102         1       10
102         2       5
102         3       2
103         1       100
103         2       60
103         3       40
401         1       1000
401         2       500
401         3       250
401         4       100
401         5       50

我正在尝试编写和执行 SQL 子查询。到目前为止,我已经想到了这个,但我似乎无法完成它以获得我想要的结果。

select event_id,
(select money from prize where ) as First, 
(select money from prize where ) as Second, 
(select money from prize where ) as Third
from prize AS prize2
group by event_id;

这是我的预期结果:

Event_id    First   Second  Third
101         120     60      30

最佳答案

假设地点等于第一、第二、第三等,那么相关的子查询可能就是您要查找的内容

select event_id,
(select money from t t1 where place = 1 and t1.event_id = t.event_id ) as First, 
(select money from t t1 where place = 2 and t1.event_id = t.event_id ) as Second, 
(select money from t t1 where place = 3 and t1.event_id = t.event_id ) as Third
from t
group by event_id;

+----------+-------+--------+-------+
| event_id | First | Second | Third |
+----------+-------+--------+-------+
|      101 |   120 |     60 |    30 |
|      102 |    10 |      5 |     2 |
|      103 |   100 |     60 |    40 |
|      401 |  1000 |    500 |   250 |
+----------+-------+--------+-------+
4 rows in set (0.00 sec)

但这是对 group by 的无效使用,因为没有进行聚合。并且您需要应用 where 子句以限制为 even_id 101。

关于mysql - 在 SQL 中编写和执行子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56888304/

相关文章:

MySQL 对一个非常简单的查询不返回任何内容

c# - 不支持 EF6 嵌套事务

mysql - 我可以单独存储重复的 sql 查询并在模型中的函数内调用它们 - Codeigniter

mysql - 在设定的时间删除行

PHP 无法重定向到某些页面

php - 如何使用php循环将mysql中的数据更新为null?

c# - MYSQL 空值干扰 C# 应用程序

mysql - SQL 不同的问题

python - Django 模型中的多对多关系

mysql - 将 Spring Boot 应用程序连接到 Google Cloud 中的 MySQL 数据库