In my application I have 2 tables in the DB (MySQL):
Companies and News. Company has many News.
Company can have a set of pictures which will be displayed on the company "view page" alongside with all relative information about this company.
I've added a Photos table with next fields: id company_id filename
My question is: Now I also need to have pictures which will belong to News.
I should add another table, which will be called for example Media or I should add additional field (type) to my Photos table, rename company_id to foreign_id and then filter results in PHP and build more complex queries with for example AND 'type' = 1 to fetch photos related to Company and 'type = 2' to fetch photos related to news.
What is a better approach?
You should take the company_id field out of the Photos table and create two new tables, CompanyPhotos with id, photo_id, company_id fields, and another NewsPhotos with id, photo_id, news_id.
Then if you want to get the photos for a company you can do: select * from Photos p inner join CompanyPhoto cp on p.id = cp.photo_id where cp.company_id = ?.
And similary with NewsPhoto: select * from Photos p inner join NewsPhoto np on p.id = np.photo_id where np.news_id = ?.
It is always good to normalize databases. In the beginning it was just about tables with all data and it has evoluted to linked tables with common fields.
Hence, I strongly recommend you to have the table Photos.
After all, you have to make the basic question: can a photo belong to different news? Can a news have different pictures? If both questions' answer is "yes", you have a N:M relation, which is resolved with a middle table containing an id from every table.
You could use UUIDs as your primary key. Because they are unique application-wide (if you create them with CakePHP), you could just use a parent_id column in your Photos table and get rid of the type colum.
Another approach would be MySQL Views. You could setup 2 Views (e.g. NewsPhotos, CompanyPhotos) on top of the Photos table. CakePHP handles (simple) Views like tables, so you could create easily Models & Controllers for this.
Related
I am currently making an android app which uses a feed to display statuses made by users. I have three tables within the same database, each has username either as a primary or unique key column, but each table has different information relating to that user.
For instance, the first table ===>> tbl_users:
username
fname (first name)
mname (middle name)
lname (last name)
etc. (the list is long)
The second table ===>> tbl_userprofilepictures:
profilepictureID
username
profilepicturepath
The third table ===>> tbl_user_feed:
postID (the status' unique ID)
username
status
imagepostpath (the path to the image uploaded with the status)
timestamp
I want to be able to search for the username across all three tables and display the relevant information relating to them on their post. For example I will need their name and surname for tbl_users and I will need their profilepicturepath for tbl_userprofilepictures as well as their status, imagepostpath and timestamp from tbl_user_feed.
Would I need to do this in a seperate PHP file or in the app itself? PS I'm fairly noob at PHP so please feel free to help a bro out.
May the force be with you.
You can use JOIN.
What is JOIN ?
An SQL JOIN clause is used to combine rows from two or more tables, based on a common field between them.
Source : w3schools.com Joins
Here is the sample I made base on your tables given. For these one our common field is username.
SELECT CONCAT('a.fname', 'a.lname'), b.profilepictureID, c.status, c.imagepostpath, c.timestamp
FROM
tbl_users as a
LEFT JOIN tbl_userprofilepictures as b ON b.username = a.username
LEFT JOIN tbl_user_feed as c ON c.username = a.username
Using Alias (table_name as custom_name) is a good practice in joining the tables
I want to retrieve one complete object from VIDEOPLAYLIST that contains the complete USER object and all the VIDEO objects related to it.
I understand that I will need to use LEFT JOIN to merge them, but I cant understand how i should setup my PLAYLIST table and how to query it when it comes to multiple VIDEO id's.
This is my current database EER Diagram:
Should I create a many to many relationship between the playlist and video?
Should I somehow store all the VIDEO id's in the PLAYLIST table?
And then how would be able to query it?
This is where I'm stuck:
SELECT * FROM videoplaylist LEFT JOIN user LEFT JOIN video ON user.id = playlist.user_id AND videos....
PS. I won't just be querying one PLAYLIST at the time, as I need to display them in a list format.
Yes, you should create a many-to-many relationship between the video and playlist table if you want that one video could be added to multiple playlists and vice versa.
So your many-to-many relationship table could look like this where the combination of playlist_id and video_id is your primary key.
playlist_has_video
------------------
playlist_id
video_id
If you want to be able to add a video more than once to a playlist you have to create an id col in this table too. So now id is your primary key.
playlist_has_video
------------------
id
playlist_id
video_id
When you want to enable the user to sort the playlist think about adding another col order_id to your n-to-m table.
playlist_has_video
------------------
id
playlist_id
video_id
order_id
Now lets see the select queries (i will refer to the last design, id + order_id)
retrieving all videos from a playlist:
SELECT video.* FROM playlist_has_video AS phv LEFT JOIN video ON phv.video_id = video.id WHERE phv.playlist_id = :playlist_id ORDER BY order_id ASC;
Retrieving all playlists the video is in:
SELECT playlist.* FROM playlist_has_video AS phv LEFT JOIN playlist ON phv.playlist_id = playlist.id WHERE phv.video_id = :video_id;
You have to alter you video - table too if you use this approach (Make sure you remove playlist_id)
video
---------
id
title
description
user_id
transcript_id
created
updated
I'm trying to figure out the best approach, more specifically which JOIN to use, with my current situation:
I have two tables (entries, users) in my database. I'm querying and displaying all my news entries on one of my pages. With each entry, I'm also posting the entry information such as date, time and the author (or user) who created the entry.
In my "entries" table, I'm only inputting the user's id (user_id) as the post's author. The "users" table has all the author's information, such as name, email, etc.
Which "JOIN" statement would be best for specifically querying the "entries" table to display all my entries but to also grab certain information from my "users" table just by matching the user_id from "entries" to user_id in "users"?
Simple join statment
SELECT e.*,u.* FROM entries e JOIN users u
ON e.user_id = u.user.id
LEFT INNER JOIN probably.
it will display all from entries, and if users is atached to entries will be dispplayed aswell, else the field will be null.
For the site I'm working on, I want a user to have the ability to checkmark multiple boxes that represent things he/she might be interested, similar to StumbleUpon. A user would check 'web development' and 'web design' then click 'Submit', which would then store his preferences in a database.
Later, if somebody created a project that was tagged with one of the preferences he selected, that user would get an update. So if I made a new project that said "Building a Website" and checked the category "web development", all users who had "web development" selected on their personal profiles would get some kind of message or email alerting them to the newly created topic.
What is the best way to implement this in MySQL format? I looked at some pages on managing hierarchical data (there will be generalized categories like "Computers" or "Music" and an admin will be able to add/delete/edit categories), but none of the methods seemed to be what I needed - at least, not in the way of thinking I'm stuck in. Perhaps there's an easier answer out there that I've been overlooking?
Create a table containing the various interests. Say
Interests :- id, interest
Then a table which stores all the interests selected by a user as
UserInterests :- user_id, interest_id
And a project interest relation as
ProjectInterest :- project_id, interest_id
Now when a new project is added you can run a query similar to the following onw to get the users that the project is of interest
SELECT DISTINCT user_id
FROM UserInterests ui, ProjectInterests pi
WHERE ui.interest_id = pi.interest_id AND pi.project_id = <new project id>
Or, using the explicit join syntax:
SELECT DISTINCT user_id
FROM UserInterests ui
INNER JOIN ProjectInterests pi ON ui.interest_id = pi.interest_id
WHERE pi.project_id = <new project id>
What you are asking - I think - is how to implement a many-to-many relationship.
The problem is that you can't give a user a list of interests without locking yourself into an exact number of interests they can select.
The solution is a Junction Table. On one hand, you have your list of users, and on the other hand, you have your list of interests. The junction table is a third table that lists the relationship between these two groups.
CREATE TABLE `user_interest` (
userid UNSIGNED INT REFERENCES `user` (userid),
interestid UNSIGNED INT REFERENCES `interests` (interestid),
PRIMARY KEY (interestid, userid)
)
Now you have a list of UNIQUE combinations of users and interests. Let's say you have a list of news articles, each with a single topic ("interestid") assigned to it. Now you can do something like,
SELECT * FROM `article` WHERE `article`.`interestid` IN (
SELECT `interestid` FROM `user_interest` WHERE `userid` = X
)
Which will retrieve the list of articles related to user X's selected interests. First, you get the list of topics that were related to your specified user, then you get the list of articles with matching topics.
Intro
Hello! I am in the process of building a lyrics website where I will store the lyrics in a MySQL database.
I want to have 2 main tables: 1 for the lyrics which will have id, lyrics title, lyrics text, artist name,and number of views.
The other table will be the artist table with: id, artist name
QUESTIONS:
How can I link the two tables by using the artist name field in both table? I want to display all the artists on my site from the table and see all the lyrics related to that particular artist/
How can I link to a particular record or field in a table?
Please help or if you know of any sites or videos that can help me learn these and other things that may help me in building my site would be appreciated.
Do not store the artist name in both tables. That defeats the purpose of having a separate artist table. Instead store the ArtistID in the Lyrics table, and only store the ArtistName in the Artist table. That way if you, for example, misspell an artist's name, you will only have to update one table, and you will not break the relationship between Lyrics and Artist.
Tables are linked together using Foreign Key relations.
I answer first question.
You should really change your lyrics table using an id_artist field instead of artist name.
This makes sure you don't duplicate names (so wasting space) and you can't write a wrong name leading you to wrong result during queries.
So you can do
SELECT a.`artist name`, l.title, l.text
FROM artist a INNER JOIN lyrics l
ON a.id = l.id_artist
WHERE a.name = '....'
// or you can use WHERE a.id = ...