2016-05-18 4 views
1

Ich habe ein Benutzermodell und ein Standortmodell. Ich möchte die erste ocurrence ihrer Lage in der Ortstabelle alle Benutzer zeigen, wieRuby Abfrage Fehler

User 
user_id name location_id 
1   tim  1 
2   adam 2 
3   Joy  3 

Location 
location_id name 
1   NewYork 
2   NewYork 
3   NewYork 

Expected Ouput:

User 
user_id name location_id 
1   tim  1 
2   adam 1 
3   Joy  1 

gezeigt Ich habe versucht, diese Abfrage auszuführen, aber es ist nicht arbeiten:

User.joins(:location).update_all("location_id =(select id from locations as l2 where l2.name = locations.name limit 1)") 

Fehler:

ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: invalid reference to FROM-clause entry for table "locations" 
LINE 1: ... =(select id from locations as l2 where l2.name = locations.... 
                  ^
HINT: Perhaps you meant to reference the table alias "l2". 

Alle soluti auf?

+0

Standorte existieren für diesen Kontext nicht. locations.name funktioniert nicht. Versuchen Sie Folgendes: User.joins (: location) .update_all ("location_id = (Wählen Sie die ID aus den Speicherorten l2 aus. L2.name = (Wählen Sie den Namen aus den Speicherorten l3 mit l3.id = users.location_id limit 1) limit 1)") –

+0

vielleicht werden die Benutzer aber brechen ... und dann müssen Sie noch eine Abfrage stellen :(Aber ich denke, Sie sollten auch nach einer Lösung suchen, die versucht, die Tabellen in der aktiven Rekordweise Alias ​​... und dann alias Benutzer und Standorte von Anfang an –

Antwort

0

So würde ich erwarten, dass es in SQL funktioniert;

SELECT 
a.user_id 
,a.name 
,fst.ID AS location_ID 
FROM locations a 
LEFT JOIN (SELECT name, MIN(location_id) ID FROM locations GROUP BY name) fst 
ON a.name = fst.name