2016-09-26 7 views
-1

ユーザーは複数の場所を持っていますが、少なくとも1つの共通の場所から認証されたユーザーを選択する必要があります。mysqlはサブクエリーで選択します。クロージャー

FE

select * from users as user where 
(select location_id from user_locations where user_id = auth()->user->id) 
'has common operator' 
(select location_id from user_locations where user_id = user.id) 

私は、彼らは共通の要素を持っている場合、2つの配列を比較したいが、私はMySQLはそのような機能を持っていないと思います

答えて

1

たぶんこの1

SELECT u.* 
FROM users u 
LEFT JOIN user_locations ul ON ul. user_id = u.id 

WHERE ul.location_id IN (
    SELECT location_id 
    FROM user_locations 
    WHERE user_id = auth()->user->id 
) 
+0

これは、別のものを選択しなくても機能しません。共通のlocation_idを持つユーザーと同じユーザーを複数選択するためです。それはまた、最適な方法ではなく、結合を使用したくありません。 – Doodles

+0

共通要素がある場合は配列と比較したいが、mysqlにはそのような関数がないと思う。 – Doodles

+0

LEFT JOINは内部結合として実行される。 – jarlh

0

をお試しくださいこれは動作します、それを試してみてください。

select * 
from users as user 
where 
exists (
    select 1 
    from user_locations ul 
    where ul.user_id = user.id 
    and exists (
     select 1 
     from user_locations ul_in 
     where ul_in.user_id = auth()->user->id 
     and ul_in.location_id = ul.location_id 
    ) 
)