根据Friends Table中的id从User表中检索数据

时间:2015-12-28 10:42:29

标签: mysql sql select join self-join

我有2个表用户和朋友。

用户表字段(id,用户名,密码,fname,lname,昵称等)

朋友表字段(id,user_id,friend_id)

现在问题是我正在尝试根据朋友表friends_id访问用户数据。

mysql查询是:

SELECT *
FROM Users
inner JOIN Friends
ON Users.ID=Friends.Friend_ID;

但需要所有用户数据。

2 个答案:

答案 0 :(得分:1)

您正在寻找self referential join

#app/models/user.rb
class User < ActiveRecord::Base
   has_and_belongs_to_many :friends,
     class_name: "User", 
     join_table: :friends,
     foreign_key: :user_id, 
     association_foreign_key: :friend_id
end

您必须更改friends表格以移除id列(根据has_and_belongs_to_many guidelines):

enter image description here

它可以让你打电话:

#config/routes.rb
resources :users do
   resources :friends, only: [:create, :destroy] #-> url.com/users/:user_id/friends
end

#app/controllers/friends_controller.rb
class FriendsController < ApplicationController
   before_action :set_user

   def create
      @user.friends << @friend
   end

   def destroy
      @user.friends.delete @friend
   end

   private

   def set_user
      @user   = User.find params[:user_id]
      @friend = User.find params[:id]
   end
end

答案 1 :(得分:0)

试试这个:

SELECT U1.id AS UserId, 
       U1.username AS UserName, 
       U1.fname AS UserFName, 
       U1.lname AS UserLName,
       U2.id AS FriendId, 
       U2.username AS FriendUserName, 
       U2.fname AS FriendFName, 
       U2.lname AS FriendLName
FROM Friends F 
INNER JOIN Users U1 ON F.user_id = U1.id
INNER JOIN Users U2 ON F.Friend_ID = U2.id;