How implement one-to-many objects database in sqlite for android

后端 未结 3 852
栀梦
栀梦 2021-01-02 03:59

I\'m quite new to SQLite and SQL and I am struggling with how to approach the following:

My app will display a list of community members. I

相关标签:
3条回答
  • 2021-01-02 04:41

    You need to have two tables:

    1.Users

    USER_ID | NAME

    2.TWEETS

    USER_ID | TIME | MESSAGE

    Now for the explanation:

    Table 1 is represents the users, there is all the data about the user, like name, phone, address etc.

    Table 2 is for all the tweets of all the users, and there is a column that connects between user and his tweet. In table 2 USER_ID is foreign key, that points to exactly one row in the users table.

    To get all the tweets for one user, you can write the next query:

    Select TWEETS.MESSAGE, TWEETS.TIME
    from Users, TWEETS
    where Users.USER_ID = TWEETS.USER_ID
    and Users.NAME = "Pierre";
    
    0 讨论(0)
  • 2021-01-02 04:49

    This is a typical "JOIN" scenario where you have a one-to-many relationship between Users and Posts.

    Here is an example of a query that would display all users and their posts:

    SELECT u.User_ID, u.Name, p.Time, p.Message
    FROM Users u INNER JOIN Posts p ON u.User_ID = p.User_ID
    

    This will produce a resultset with four columns. Each "Tweet" will be displayed with its related User record. The 'u.' and 'p.' syntax are table aliases used to make the query easier to read.

    0 讨论(0)
  • 2021-01-02 04:57

    An answer has been given and accepted already, but I wanted to add this.

    What you want is one table with users, users. In this table you store your user information (user_id, name).

    In your Tweets table, store all tweets for all users. One tweet per row. I'm using tweet_id as PRIMARY KEY for the Tweets table.

    You can then 'link' the two in code by doing a JOIN like Dave Swersky said.

    For example:

    Users
    --------------------------
    user_id   |   user_name
    --------------------------
       123    |    'Terry'
       34     |    'Pierre'
    
    Tweets
    -----------------------------------------------------------------------
    tweet_id |   user_id   |  time      |         message     
    -----------------------------------------------------------------------
       0     |    123      | 135646     |  'This is a tweet'
       1     |    123      | 132646     |  'This is another tweet by Terry'
       2     |    34       | 352646     |  'Pierre\'s tweet'
    

    I'm not sure what name is for in your Tweets table. As far as I know tweets do not have a name/subject(?). You do not need to store the user name in both the tweets and users table.

    For a quick SQLFiddle, go here: http://www.sqlfiddle.com/#!2/43492/1/0

    Join

    SELECT u.user_id, u.name, t.time, t.message, t.time 
    FROM my_users u
    INNER JOIN tweets t ON u.user_id = t.user_id
    
    0 讨论(0)
提交回复
热议问题