I am making an Android app that will use a friends list. As far as I know, you can't store an array in a MySQL table, so it seems that I will have to make a separate table from my "Users" table and call it, say, "Friends". This table will just have Friend1 and Friend2.
My question is the preferred way to store this table. I can use the UserName field (string) from my "Users" table to store them, or I could use the UserID field (integer) from my "Users" table. Using the ID would make the table smaller because the small integers take up more space than the string, but at the same time, I access this data mainly using the UserName field (so I have to query the Users table to get the UserID from the Users table).
Which method is preferred for a MySQL table? Using the users name directly so I do not have to find the UserID from the Users table, or saving the table as two integers, and querying to find the ID from the UserName? Thanks.
Store two userID keys from the users table.
Let's say that you change a name of a contact from "Guy from bar" to "Mr. McMoneypants". If this contact was a friend, it will still show up as "Guy from bar" even after the change.
Try to keep data from living in multiple places.
The preferred method is to use the UserID from the Users table in the Friends table as a way to reference that user. That way, as Phillip says, the User can change their name and you only have to change it in one place. Plus, as you say, your Friends table will take up less space with a numeric column as compared to a string column.
And in regards to "(so I have to query the Users table to get the UserID from the Users table)", the following query is not too cumbersome:
SELECT FriendName
FROM Users Natural Left Join Friends
WHERE UserName = 'Ralph';
As far as your query is concerned, you never had to deal with the UserID column.
That's not that much harder than your method:
SELECT FriendName
FROM Friends
WHERE UserName = 'Ralph';
Related
I'm using moor_flutter to persist my data in an SQLite database in my Flutter application. One of my columns for the sake of argument looks like this:
class Clients extends Table {
// Autoincrement automatically sets this to be a primary key
IntColumn get id => integer().autoIncrement()();
TextColumn get name => text().withLength(min: 1, max: 60)();
TextColumn get phone => text().withLength(min: 1, max: 50)();
}
I'm looking to store an array of clients I have recently opened in a List of length 10. Every time somebody would interact with that client, the list would place that client on the top of the list and remove the last one so that it would always be 10. It could also reorder them to bubble one from the middle, up to the top.
In any case, what I'm looking to do is create a new table called "Recents" which would have a single field of type List like so:
class Recents extends Table {
List<Client> recents => List<Client>[10].withLength(min: 0, max:10)()();
}
I couldn't find anything usable on the interwebz so here we are StackOverflowers! How would you solve this conundrum?
There isn't any good way in the SQLite database to store a list in a single column of a table the natural way is to store list items in the other table which every single row represents a single item of your list and connect that with a relation to other tables for example for if consider a scenario which we have a Users table and each user entity have a list of phone numbers that associated with we can store all the users in the Users table and store all the phone numbers in other table and we will create a userId column in the phone numbers table and we add a userId for each phone number that indicates this phone number is associated with the specific user with unique userId "the relation" and this way when we want to get a phone numbers list for a user we can query phone numbers table for the phone numbers that have specific userId
Users Table
UserId
Username
0
A
1
B
3
C
Phone Numbers Table
Id
PhoneNumber
UserId
0
+099888
0
1
+121181288
0
2
+31188218
0
3
+121221295
1
4
+9852121328
2
5
+2512165
2
the second way you can handle this scenario is converting your List to a type that is supported in SQLite for example convert your list items to a JSON string and insert that as text into a column of a user table and when you read this field you can convert it to a List of items, Most of ORM's will provide a tool that helps you with us a secnario
for a moor, you can use a converter here is the link to the documentation
https://moor.simonbinder.eu/docs/advanced-features/type_converters/
But notice that this approach is less flexible for example you
can't query on the phone numbers and it has a bad effect on performance
I currently have an app where I store user data in a SQLite database, and one of my fields is a User ID. I would like to add an option to auto-generate User IDs in an mmddyyXXX format, where XXX is a sequential number per user that resets every day.
Does anyone know how I would approach this? I looked at some of the other similar questions, but they don't seem to be helpful.
This is not complicated at all. If your'e similar with SQLite in android just take the date and the userId using a SELECT and generate that string yourself.
If the XXX is not the userId just save another table containing 'tokens' for users. every userId would have a 'token'.
Every new day just change the contents of this table.
I believe you could use a TRIGGER that will generate the userid when a row is inserted.
The following may suit :-
CREATE TRIGGER IF NOT EXISTS newuserid AFTER INSERT ON users
BEGIN
UPDATE users SET userid = strftime('%m%d',date('now'))||substr(strftime('%Y',date('now')),3)||
(
SELECT CAST(substr('000',1,3-length(count()+1)) AS TEXT)||CAST((count()+1) AS TEXT)
FROM USERS
WHERE substr(userid,1,6) = strftime('%m%d',date('now'))||substr(strftime('%Y',date('now')),3)
)
WHERE userid IS NULL;
END;
The trigger is named newuserid
userid is the column for the auto-generated id. The above relies upon it being NULL so it cannot be a PRIMARY INDEX.
There is no reliance upon other columns.
Testing
Starting with an empty table :-
Inserting 4 rows using INSERT INTO users VALUES(null,'This is a new user'); results in :-
To check for another date the rows are adjusted from 041018??? to 040918??? as per :-
4 more rows are inserted using INSERT INTO users VALUES(null,'This is a new user');, resulting in :-
Note this answer isn't intended to be fail-safe but rather the basis of the concept for the answer.
I'm trying to build a chore app where the user can create a group with a password and they can then add chores to the group that they made. My question is I'm using sqlite as the database and I'm wondering if it's possible to add a database column into the table. I'm planning on creating a table inside my db with columns of id, username, password, database. database is where I will create additional databases where it will store the chore table for my app. If I can't do this, can someone lead me along the way on how I can for example, make a table named Group, then for its columns have id, username, password. Then for each Group rows, be able to somehow match it with another corresponding database or table where the table will be chores with columns say name, frequency. And however many Group rows I add, I will need to somehow make another chore table to match with it, but I need to know how to link and refer to it from just my Group table. If there's a better way to do this using SQLite I would love to know. Thank you.
If i get your question correctly, I think all u need is to use PRIMARY_KEY and FOREIGN_KEY. Hope you are aware of constraints in databases.
So basically two tables will share a KEY which is unique, the key will be the PRIMARY_KEY in table 1 and will act as a link or reference to row in second table, where it is a FOREIGN_KEY
check this for more on constraints
The goal is : after a user has been logged in , the next activity should display his list of courses.
There is a table of courses in Parse's cloud, but how can I retrieve the correct courses (current user's courses) ?
I've thought of 2 approaches :
1. using getCurrentUser method - but what if there are more than one user in the cache ?
2. save for each course the userName that saved it , and then query for that userName - but how should I know that the currentUser method will return the correct user ?
How can I solve this problem ?
using getCurrentUser method - but what if there are more than one user in the cache ?
There's always one currently logged in user and ParseUser.getCurrentUser() will get it. Well, unless there is no logged in user.
but how should I know that the currentUser method will return the correct user
As above. I don't get what you're confused about.
There is a table of courses in Parse's cloud, but how can I retrieve the correct courses (current user's courses)
and
save for each course the userName that saved it , and then query for that userName - but how should I know that the currentUser method will return the correct user ?
I can think of two approaches here. There may be more. Up to you what you decide to use.
So you have the _User table and the Course table. You can do one of the following:
Add a courses array to each _User and for each _User, store their list of courses there. It should be a list of objectIds, so basically you'll have the ID's of all the courses that _User is registered for. Each Parse object has a limited size in the database so you should use it if you are sure you won't need big amounts of data for each user. If you want to retrieve this, query the _User table by the id of the user and fetch the list of courses.
The "relational" approach: add an UserCourse table that has a userId and a courseId column. Every time you want to add a course for a particular user, you add a new entry in here that holds the id of that user and the id o the course. Similarly to the above, have a query that fetches all the stuff from UserCourse by userId. Note that in this case you'll also need to make sure your query fetches the data from _User and Course. Otherwise you'll just end up with UserCourse entries, which merely store ID's.
In my application ,am work with a large database.Nearly 75000 records present in a table(totally 6 tables are there).i want to get a data from three different table at a time.i completed that.but the search process was slow.how can i optimise the searching process?
You might want to consider using the full-text search engine and issuing SELECT...MATCH queries instead. Note that you need to enable the FTS engine (it's disabled by default) and create virtual tables instead of regular tables. You can read more about it here.
Without being able to see the table structure (or query) the first thing I'd suggest is adding some indexes to the tables.
Lets say you have a few tables like:
Author
id
last_name
first_name
Subject
id
name
Book
id
title
author_id
subject_id
and you're wanting to get all the information about each of the books that an author with last_name="Smith" and first_name="John" wrote. Your query might look something like this:
SELECT * FROM Book b
LEFT JOIN Subject s
ON s.id=b.subject_id
LEFT JOIN Author a
ON a.id=b.author_id
WHERE a.last_name='Smith'
AND a.first_name='John';
There you'd want the last_name column in the Author table to have an index (and maybe first_name too).