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 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏