简体   繁体   English

MySQL子查询,其中少于3个,且放置不止一次

[英]MySQL Subqueries where less than 3 and places more than once

I have two tables i need to query One called horse which contains the Name and Horse_id One called entry which contains the Horse_id and the Place. 我有两个表需要查询:一个叫马,其中包含名称和Horse_id;一个叫条目,其中包含Horse_id和Place。 (Place is the where the horse came, eg. 1st, 2nd, 3rd). (地点是赛马的出发地,例如1号,2号,3号)。

I need to use a subquery to display the horse Name and Id of every horse that has won a 1st 2nd or 3rd more than once. 我需要使用子查询来显示每一次赢得第一名第二名或第三名以上的马匹的马名和ID。

So far i have (i haven't gotten to the "more than once" part yet) 到目前为止,我已经(我还没有参加“不止一次”的部分)

SELECT horse_id, name FROM 
(SELECT count(place) AS horse_id, name FROM entry)
WHERE entry.place<3;

Although this isn't working. 虽然这不起作用。 Error is "every derived table must have its own alias". 错误是“每个派生表必须具有自己的别名”。 I'm not sure what i'm supposed to name and i'm finding it hard to find examples of this type of query. 我不确定我应该命名什么,而且我发现很难找到这种查询的示例。

I also tried: 我也尝试过:

SELECT horse_id, name FROM horse
WHERE place IN(SELECT horse_id FROM entry WHERE entry.place<3);

Not sure where i'm going wrong 不知道我要去哪里错了

I apologize, should have read the question better.. just created the tables on my system this works: 抱歉,应该更好地阅读该问题..刚刚在我的系统上创建了表,这可以正常工作:

select name, horse_id 
FROM horse LEFT JOIN 
(select horse_id, count(horse_id) as c FROM entry where place < 4 group by horse_id) as h 
USING (horse_id) WHERE c > 1;

The Simplest solution would be: 最简单的解决方案是:

SELECT horse_id, name FROM 
(SELECT count(place) AS horse_id, name FROM entry WHERE entry.place<3) as cute_little_ponies;
SELECT horse_id, name, SUM(IF(place<=3,1,0)) AS top_3_count
FROM horse
JOIN entry USING (horse_id)
GROUP BY horse_id
HAVING top_3_count > 1
SELECT Horse_id,Name FROM HORSE
WHERE Horse_id IN 
(SELECT Horse_id FROM ENTRY WHERE Place IN (1,2,3) GROUP BY Horse_id HAVING COUNT(Horse_id)>1); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM