我正在用Rails编写查询。我有名为School and Skill的表格。 技能有专栏
id: integer
name: text
school_id: integer
我有@skills,其中包含一些行。但是@skills可以有重复的名称。
我想从@skills中删除重复的行,其中school_id == 1。
例如,如果@skills返回
#<ActiveRecord::Relation [#<Skill id: 249, name: "3 D Priniting", school_id: 1>,
#<Skill id: 258, name: "Cinematography", school_id: 11>,
#<Skill id: 174, name: "Sports", school_id: 1>,
#<Skill id: 259, name: "Cinematography", school_id: 1>,
#<Skill id: 300, name: "Sales", school_id: 11>,
#<Skill id: 301, name: "Marketing", school_id: 11>,]
此处的技能ID 258和259具有相同的名称。所以我想删除259,因为它具有school_id == 1。
我使用了以下SQL查询,但是它选择了MIN(id)。
SELECT MIN(id) as id, school_id
FROM `skills`
GROUP BY `skills`.`tag_id`,
`skills`.`tag_type`, `skills`.`school_id`, `skills`.`master_tag_id`
我可以这样删除重复项吗?我想在一个查询中完成此操作。
注意:感谢ActiveRecord中的解决方案。
答案 0 :(得分:1)
您可以尝试以下查询:
set @lagName := '';
set @rn := 0;
select id, name, school_id from (
select
case when @lagName = name then @rn:=@rn+1 else @rn:=1 end rn,
@lagName:=name,
id,
name,
school_id
from Skills
order by name, school_id desc
) a where rn=1
它根据name
列在组内使用行编号。每个组然后按school_id
进行排序,因此school_id
排在最后。然后选择rn
等于1的那些记录就足够了。
答案 1 :(得分:1)
import pygame
black = (0,0,0)
white = (255,255,255)
gray = (128,128,128)
red = (255,0,0)
pygame.init()
gameDisplay = pygame.display.set_mode( (800,600))
clock = pygame.time.Clock()
def button(msg,x,y,w,h,ic,ac,action=None):
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if x+w > mouse[0] > x and y+h > mouse[1] > y:
pygame.draw.rect(gameDisplay, ac, (x,y,w,h))
if click[0] == 1 and action != None:
action()
else:
pygame.draw.rect(gameDisplay, ic, (x,y,w,h))
smallText = pygame.font.SysFont("comicsansms",20)
textSurf = smallText.render(msg, True, red)
textRect = textSurf.get_rect()
textRect.center = ( (x+(w/2)), (y+(h/2)) )
gameDisplay.blit(textSurf, textRect)
def change_draw_to_intro():
global draw
draw = draw_intro
def change_draw_to_other():
global draw
draw = draw_other
def change_draw_to_BE01():
global draw
draw = draw_BE01
def draw_BE01():
gameDisplay.fill(white)
#gameDisplay.blit(BE01Img,(0,0))
button("BACK",350,450,100,50,black,gray,change_draw_to_intro)
def draw_intro():
gameDisplay.fill(white)
#gameDisplay.blit(introImg,(0,0))
button("START",350,450,100,50,black,gray,change_draw_to_other)
def draw_other():
gameDisplay.fill(white)
#gameDisplay.blit(scene01Img,(0,0))
button("1",200,450,100,50,black,gray,change_draw_to_BE01)
def quitgame():
pygame.quit()
quit()
def game_loop():
global draw
draw = draw_intro
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
draw()
pygame.display.update()
clock.tick(60)
game_loop()
pygame.quit()
quit()
答案 2 :(得分:0)
使用子查询方法。第一组@skills表使用Schol_id和名称。然后执行实际的选择语句。
select * from skills where id in (select id from skills group by school_id, name);