Reputation: 623
Hello I'm working on a Management Restaurants project on Android Studio using Java , and since I have 6 types of categories , I want to group them on a specific type in my Database table
like we do in MySQL Enum
type , and of course access to them later .
Here's my table code on Java, and I'm using SQLite
as a database :
public static final String CREATE_RESTAURANT_TABLE_ =
"CREATE TABLE " + RESTAURANT_TABLE + "(" +
ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
NAME + " TEXT " +
CITY + " TEXT " +
CATEGORY + "TEXT" +
PHONE_NUMBER + "TEXT" +
LAT + "TEXT" +
LON + " TEXT );";
Upvotes: 3
Views: 2026
Reputation: 164139
There is no ENUM
data type in SQLite, but even if there was one it would not be the best way to define this column.
What if you want to add a new category? You would have to redefine the enum values in the table's definition and this is not possible in SQLite unless you recreate the table (as you can find here).
The proper design in this case is to create a table categories
like:
CREATE TABLE categories(id INTEGER PRIMARY KEY, category TEXT);
and store all the categories there:
INSERT INTO categories(category) VALUES
('category1'), ('category2'), ...., ('categoryn');
and in your RESTAURANT_TABLE
define a column that references the column id
of categories
:
public static final String ID_CATEGORY = "id_category";
public static final String CREATE_RESTAURANT_TABLE_ =
"CREATE TABLE " + RESTAURANT_TABLE + "(" +
ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
NAME + " TEXT," +
CITY + " TEXT," +
ID_CATEGORY + " INTEGER REFERENCES categories(id)," +
PHONE_NUMBER + " TEXT," +
LAT + " TEXT," +
LON + " TEXT);";
In your SQLiteOpenHelper
class you must enable foreign key constraints by overriding onConfigure()
like this:
@Override
public void onConfigure(SQLiteDatabase db) {
db.setForeignKeyConstraintsEnabled(true);
}
Now, in the column id_category
of the restaurants table you will store ids which are references to the categories that you have in the categories
table.
You can add new categories in categories
without any problem.
When you query the table restaurants and you want to retrieve each row's category you must join the 2 tables:
SELECT r.id, r.name, r.city, c.category, r.phone_number, r.lat, r.long
FROM restaurants AS r INNER JOIN categories AS c
ON c.id = r.id_category
Upvotes: 3