2017-02-24 4 views
-1

私はPHPとMySQLを使用しています。私はテーブル '通知'とテーブル 'ユーザー'を持っています。通知は送信者と受信者を指定します。私はいくつかの研究をしていくつかのことを試しましたが、私は解決策には出ませんでした。次のSQLクエリは通知のデータセットと受信者データを提供しますが、どのようにして1つのクエリでユーザーテーブルから送信者データを選択することもできますか?1つのSQLクエリを使用して送信者(データ)と受信者(データ)を選択する方法はありますか?

SELECT notifications.id,notifications.recipient_id,notifications.sender_id,notifications.unread,notifications.type,notifications.parameters,notifications.created_at,users.id AS user_id,users.username 
FROM notifications, users 
WHERE users.id = notifications.recipient_id; 

答えて

1
SELECT 
    notifications.id, 
    notifications.recipient_id, 
    notifications.sender_id, 
    notifications.unread, 
    notifications.type, 
    notifications.parameters, 
    notifications.created_at, 
    users1.id AS user_id_recipient, 
    users1.username AS username_recipient, 
    users2.id AS user_id_sender, 
    users2.username AS username_sender 
FROM notifications 
INNER JOIN users AS users1 ON users1.id = notifications.recipient_id 
INNER JOIN users AS users2 ON users2.id = notifications.sender_id 
+0

私は、次のエラーを取得しています: –

+0

#1064 - あなたのSQL構文でエラーが発生しているが、あなたのMySQLサーバのバージョンに対応するマニュアルをチェックし、適切な構文を使用して '.username_recipient、users2.id AS user_id_sender、users2.username AS'と入力してください。10行目 –

+0

を編集しました。答えの内容でもう一度試してみてください。 – TopCheese

関連する問題