dou8mwz5079 2017-07-08 17:28
浏览 33
已采纳

存储关注者和跟踪MySQL的最佳方式

I have 2 tables one is user and another is company. Both have the following columns common while other columns are different.

id   email                name   
1    first@email.com      First user
2    second@email.com     Second User
3    third@email.com      Third User

Now a user can follow many companies but a company does not follow back user. Company should have data with users who follow them and a user should also store the companies they are following.

What is the simplest and optimal to make this happen on MySQL? Either should I create separate table for it or just add a column on existing tables with array of followers. Please answer assuming I have working level of knowledge on PHP and MySQL.

  • 写回答

2条回答 默认 最新

  • dongqie4402 2017-07-08 17:58
    关注

    You have the tables User and Company. Let's suppose they contain these columns:

    UserId UserName UserMail
    ------ -------- --------------
    1      Alice    alice@mail.com
    2      Bob      bob@mail.com
    
    CompanyId CompanyName CompanyAddress
    --------- ----------- --------------
    1         Microsoft   Redmond
    2         Apple       Cupertino
    3         Google      Mountain View
    

    Then you should create a many-to-many table - e.g. let's call it UserCompany - which contains at least the columns UserId and CompanyId (coming from the first two tables).

    Let's suppose that Alice follows Microsoft and Apple, and Bob follows Google. Your new UserCompany table will contain the following data:

    UserId CompanyId
    ------ ---------
    1      1
    1      2
    2      3
    

    Company should have data of users who follow them

    Here you are the query to get the data of the users that follow Microsoft:

    SELECT u.UserName, u.UserMail
    FROM User AS u
    JOIN UserCompany AS uc ON u.UserId = uc.UserId
    WHERE uc.CompanyId = 1
    

    User should also have data of companies they are following.

    And here you are the query to get the data of the companies followed by Alice:

    SELECT c.CompanyName, c.CompanyCity
    FROM UserCompany AS uc
    JOIN Company AS c ON c.CompanyId = uc.CompanyId
    WHERE uc.UserId = 1
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!