LoginSignup
1
1

More than 5 years have passed since last update.

DBから重複レコードを除いて取得するSQL文

Posted at

課題

以下のSQL文でデータを取得した時に重複したデータが全て取得され結果に格納されてしまいました。

select user_id from idols where idol = any(select idol from idols where user_id = 1);

uses・・ユーザーテーブル
idols・・ユーザーが好きなアイドルを登録するテーブル
以下のSQL文ではuser_id = 1のユーザーと同じアイドルを好きなユーザーを取得しているのですが、好きなアイドルが複数被っている場合同じuser_idが複数取得されてしまいました。

解決

以下のようにdistinctを入れるだけ。

select distinct user_id from idols where idol = any(select idol from idols where user_id = 1);

以上。

参考
https://www.dbonline.jp/mysql/select/index13.html

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1