3

サブクエリを使用してメイン クエリからエントリを削除する方法がわかりません。2 つのテーブルがあります。

mysql> select userid, username, firstname, lastname from users_accounts where (userid = 7) or (userid = 8);

+--------+----------+-----------+----------+
| userid | username | firstname | lastname |
+--------+----------+-----------+----------+
|      7 | csmith   | Chris     | Smith    |
|      8 | dsmith   | Dan       | Smith    |
+--------+----------+-----------+----------+
2 rows in set (0.00 sec)

mysql> select * from users_contacts where (userid = 7) or (userid = 8);
+---------+--------+-----------+-----------+---------------------+
| tableid | userid | contactid | confirmed | timestamp           |
+---------+--------+-----------+-----------+---------------------+
|       4 |      7 |         7 |         0 | 2013-10-03 12:34:24 |
|       6 |      8 |         8 |         0 | 2013-10-04 09:05:00 |
|       7 |      7 |         8 |         1 | 2013-10-04 09:08:20 |
+---------+--------+-----------+-----------+---------------------+
3 rows in set (0.00 sec)

私がやりたいことは、users_accounts テーブルから連絡先のリストを取得することです。

1) ユーザー自身のアカウントを省略します (つまり、リストに自分の名前を表示したくありません)。

2) 「確認済み」状態が「0」のすべての連絡先を表示しますが、

3) 連絡先がたまたま「1」(リクエスト送信済み) または「2」(リクエストが確認済み) の「確認済み」ステータスを持っている場合は、それらを結果に含めないでください。

サブクエリを作成して、1 または 2 になるものを取得するにはどうすればよいでしょうか?

4

1 に答える 1

2

この時点でサブクエリは必要ないようです。次のようにテーブルを結合できます。

select u.userid, u., firstname, u.lastname from users_accounts u join user_contacts c on u.userid = c.userid where u.userid != your_user_id and c.confirmed = 0;

この一般的な例でyour_user_idは、明らかに現在のユーザーの ID を決定するためのプレースホルダーです。ただし、絶対にサブクエリを使用する必要がある場合:

select userid, username, firstname, lastname from users_accounts where userid != your_user_id and userid not in (select userid from user_contacts where confirmed = 1 or confirmed = 2);
于 2013-10-04T16:37:15.690 に答える