我有一个名为'prize'的小桌子,有3个字段,
Event_id | Place | Money
-------------------------
101 | 1 | 120
101 | 2 | 60
...等
现在带子查询的基本查询如下:
Select Event_id,
(SELECT money FROM prize WHERE place=1) AS 'First',
...等
子查询显然返回太多行(因为有几个事件)。如何将其限制为仅返回与Event_id字段对应的值?
我尝试过很多次迭代而没有成功,所以感谢任何帮助。
答案 0 :(得分:0)
将您的查询更改为: -
Select Event_id,
(SELECT MAX(money) FROM prize WHERE place=1 LIMIT 1) AS 'First',
答案 1 :(得分:0)
您需要在子查询中指定事件: -
SELECT Event_id,
(SELECT money FROM prize AS sub1 WHERE sub1.Event_id = prize.Event_id AND place=1) AS 'First',
.....
FROM prize
但是,如果事件有多行,每个地方一行,那么这将返回多行。可以使用DISTINCT来解决这个问题。
SELECT DISTINCT Event_id,
(SELECT money FROM prize AS sub1 WHERE sub1.Event_id = prize.Event_id AND place=1) AS 'First',
.....
FROM prize
然而,这不太可能有效。它将对奖品表中的每一行执行一次子查询。
一种可能的解决方案是使用聚合函数来获取特定值,具体取决于地点的值: -
SELECT Event_id,
MAX(IF(place=1, money, 0)) AS 'First',
MAX(IF(place=2, money, 0)) AS 'Second',
......
FROM prize
GROUP BY Event_id