MySQL: Structuring Notification Message System So Parts of It Can Be Clicked - mysql

For my senior design project, I am working on a project which is an application where an engineer can upload his/her design either 3D, 2D, or 1D and get votes by their customers which design looks good. The issue I am having is structuring my notification to where parts of the notification can be clicked and viewed in detail. If I want to insert a value before, in between, or at the end of the notification message like handles, do I need like a config file with custom messages in the backend and then insert the handles from the frontend? See examples 1 and 2 below.
Example 1 of what the notification should look like:
"Design {design_name} voted by {customer_name} and {50} other customers"
Example 2 of what the notification should look like:
"Your design {design_name} and {10} other designs got votes"
As you can see in the examples above, parts of it can be clicked to see in detail. In example 1, I should be able to click on 50 and view the remaining customers who voted for that particular design. Same concept applies to example 2. Any advice will be greatly greatly appreciated. Thank you.
//Notifications MySQL Table Fields
+----------+----------+----------+----------+-----------+----------+
| id | from_id | to_id | type | design_id | viewed |
+----------+----------+----------+----------+-----------+----------+
//3D Design MySQL Table Fields
+----------+----------+-------------+-------------+------------+
|design_id | user_id | description | design_name | image |
+----------+----------+-------------+-------------+------------+
//2D Design MySQL Table Fields
+----------+----------+-------------+-------------+------------+
|design_id | user_id | description | design_name | image |
+----------+----------+-------------+-------------+------------+
//1D Design MySQL Table Fields
+----------+----------+-------------+-------------+------------+
|design_id | user_id | description | design_name | image |
+----------+----------+-------------+-------------+------------+

With the design of the tables as they are, you could get the parameters by the following.
#notification_1
SELECT
design_name,
count(*) - 1 as number_of_other_voters,
voters_table.voters_name
FROM design_table
LEFT JOIN votes_table ON voted_design_id = design_id
LEFT JOIN voters_table on votes_table.voter_id = voters_table.id
WHERE design_id = 'x'
GROUP BY design_id
If you wanted to jam everything into a query, then you can do the following (although I highly suggest against it):
#notification_1
SELECT CONCAT("Design ", design_name, " voted by ", voters_table.voters_name, " and ", count(*) - 1 as number_of_other_voters, " other customers")
FROM design_table
LEFT JOIN votes_table ON voted_design_id = design_id
LEFT JOIN voters_table on votes_table.voter_id = voters_table.id
WHERE design_id = 'x'
GROUP BY design_id
Though this will get you a string, and possibly a meaningful one, this will not achieve the usability goals that you have laid out. If you are using PHP to build a web interface, for example, you would just run the first query and assign the results to a variable, then build your string with the links filled in with some IDs.
foreach($result as $row){
$notification = "Design " . $row['design_name'] .
" voted by <a href='/user/" . $row['customer_id'] . "'>" . $row['customer_name'] .
"</a> and <a href='/some_voting_page_url/" . $row['vote_id'] . "'>. " $row['number_of_other_voters'] " . other customers"
}
Any language (JS, PHP, Java, C, etc) will have the ability to load data from a query into a pre-fabricated string with the above method. The second notification would just be a count on the votes table (which you have not shown where the votes are being stored in your example)
SELECT count(*) FROM (SELECT DISTINCT design_id FROM votes_table WHERE user_id = 'x');
That's the best I can do with the tables as they are currently designed (considering you add a user table and a votes table). As pointed out by #Gilbert Le Blank in the comment on the main task, you should only have one table with the ability to mark what the dimension of the design is rather than three design tables unless the data stored in each is fundamentally different.

Related

ER_NON_UNIQ_ERROR and how to design tables correctly

I have come across this problem and I've tried to solve it few days now.
Let's say I have following tables
properties
-----------------------------------------
| id | address | building_material |
-----------------------------------------
| 1 | Street 1 | 1 |
-----------------------------------------
| 2 | Street 2 | 2 |
-----------------------------------------
building_materials
-----------------------------
| id | building_material |
-----------------------------
| 1 | Wood |
-----------------------------
| 2 | Stone |
-----------------------------
Now. I would like to provide an API where you could send a request and ask for every property that has building material of wood. Like this:
myapi.com/properties?building_material=Wood
So I would like to query database like this (I want to return the string value of building_material not the numeric value):
SELECT p.id, p.address, bm.building_material
FROM properties as p
JOIN building_materials as bm ON (p.building_material = bm.id)
WHERE building_material = "Wood"
But this will give me an error
Column 'building_material' in where clause is ambiguous
Also if I want to get property with id of 1.
SELECT p.id, p.address, bm.building_material
FROM properties as p
JOIN building_materials as bm ON (p.building_material = bm.id)
WHERE id = 1
Column 'id' in where clause is ambiguous
I understand that the error means that I have same column name in two tables and I don't specify which id I want like p.id.
Problem is I don't know how many query parametes API user is going to send and I would like to avoid looping through them and changing id to p.id and building_material to bm.building_material. Also I don't want that user has to send request to the API like this
myapi.com/properties?bm.building_material=Wood
I've thought about changing the properties table building_material to fk_building_material and changing properties table id to property_id.
I just don't like the idea that on client side I would then have to refer property's building material as fk_building_material. Is this a valid method to solve this problem or what would be the correct way of designing these tables?
The query mentions two tables, so all the columns in both tables are "on the table" for use anywhere in the query.
In one table building_material is an "id" for linking to the other table; in the other table, it is a string. While this is possible, it is confusing to the reader. And to the parser. To resolve the confusion, you must qualify building_material with which one you want; that is done with a table alias (or table) in front (as you did in all other places).
There are two ids are all ambiguous. But this is the "convention" used by table designers. So, it is OK for an id in one table to be different than the id in the other table. (p.id refers to one thing in one table; bm.id refers to another in another table.)
SELECT p.id, p.address, bm.building_material
FROM properties as p
JOIN building_materials as bm ON (p.building_material = bm.id)
WHERE bm.building_material = "Wood" -- Note "bm."

mySQL - Compare if values are equal from 2 tables

I'm a newbie and i'm trying to check if the location in STUDENT table is equal to the location of the QR. Anyone knows how to do this?
Student TABLE
|Student_ID|Name|Gender|Location|
---------------------------------
| 0118210 |Dex | Male | PJU1/42|
QR Table
|QR_Code|Date Generated|QR_Location|
------------------------------------
| 4747 | 4/6/2018 | PJU1/42 |
EDIT
Sorry for the lack of information given. Basically i would need to build a backend system using Laravel that would generate a QR CODE. Whenever i generate the QR Code, a unique "QR_CODE" would be generated and insert into the QR Table along side with the "Date Generated" and "QR_Location". So whenever i use my mobile phone to scan the QR Code i would like to check if my current location is equal to the location of the location of the QR_Location.
Hope that this would give u guys some idea of what i am trying to achieve.
Thank you
There are plenty of way to do this. But i would do this as
select s.*
from Student s
where exists (select 1 from QR q where s.Location = q.QR_Location);

Database design and query optimization/general efficiency when joining 6 tables in mySQL

I have 6 tables. These are simplified for this example.
user_items
ID | user_id | item_name | version
-------------------------------------
1 | 123 | test | 1
data
ID | name | version | info
----------------------------
1 | test | 1 | info
data_emails
ID | name | version | email_id
------------------------
1 | test | 1 | 1
2 | test | 1 | 2
emails
ID | email
-------------------
1 | email#address.com
2 | second#email.com
data_ips
ID | name | version | ip_id
----------------------------
1 | test | 1 | 1
2 | test | 1 | 2
ips
ID | ip
--------
1 | 1.2.3.4
2 | 2.3.4.5
What I am looking to achieve is the following.
The user (123) has the item with name 'test'. This is the basic information we need for a given entry.
There is data in our 'data' table and the current version is 1 as such the version in our user_items table is also 1. The two tables are linked together by the name and version. The setup is like this as a user could have an item for which we dont have data, likewise there could be an item for which we have data but no user owns..
For each item there are also 0 or more emails and ips associated. These can be the same for many items so rather than duplicate the actual email varchar over and over we have the data_emails and data_ips tables which link to the emails and ips table respectively based on the email_id/ip_id and the respective ID columns.
The emails and ips are associated with the data version again through the item name and version number.
My first query is is this a good/well optimized database setup?
My next query and my main question is joining this complex data structure.
What i had was:
PHP
- get all the user items
- loop through them and get the most recent data entry (if any)
- if there is one get the respective emails
- get the respective ips
Does that count as 3 queries or essentially infinite depending on the number of user items?
I was made to believe that the above was inefficient and as such I wanted to condense my setup into using one query to get the same data.
I have achieved that with the following code
SELECT user_items.name,GROUP_CONCAT( emails.email SEPARATOR ',' ) as emails, x.ip
FROM user_items
JOIN data AS data ON (data.name = user_items.name AND data.version = user_items.version)
LEFT JOIN data_emails AS data_emails ON (data_emails.name = user_items.name AND data_emails.version = user_items.version)
LEFT JOIN emails AS emails ON (data_emails.email_id = emails.ID)
LEFT JOIN
(SELECT name,version,GROUP_CONCAT( the_ips.ip SEPARATOR ',' ) as ip FROM data_ips
LEFT JOIN ips as the_ips ON data_ips.ip_id = the_ips.ID )
x ON (x.name = data.name AND x.version = user_items.version)
I have done loads of reading to get to this point and worked tirelessly to get here.
This works as I require - this question seeks to clarify what are the benefits of using this instead?
I have had to use a subquery (I believe?) to get the ips as previously it was multiplying results (I believe based on the complex joins). How this subquery works I suppose is my main confusion.
Summary of questions.
-Is my database setup well setup for my usage? Any improvements would be appreciated. And any useful resources to help me expand my knowledge would be great.
-How does the subquery in my sql actually work - what is the query doing?
-Am i correct to keep using left joins - I want to return the user item, and null values if applicable to the right.
-Am I essentially replacing a potentially infinite number of queries with 2? Does this make a REAL difference? Can the above be improved?
-Given that when i update a version of an item in my data table i know have to update the version in the user_items table, I now have a few more update queries to do. Is the tradeoff off of this setup in practice worthwhile?
Thanks to anyone who contributes to helping me get a better grasp of this !!
Given your data layout, and your objective, the query is correct. If you've only got a small amount of data it shouldn't be a performance problem - that will change quickly as the amount of data grows. However when you ave a large amount of data there are very few circumstances where you should ever see all your data in one go, implying that the results will be filtered in some way. Exactly how they are filtered has a huge impact on the structure of the query.
How does the subquery in my sql actually work
Currently it doesn't work properly - there is no GROUP BY
Is the tradeoff off of this setup in practice worthwhile?
No - it implies that your schema is too normalized.

In MySQL, How do you dynamically SELECT the values of one table, as columns in another?

I'm no MySQL guru, but I get around the basic stuff pretty well. Thanks for your feedback.
I have two tables user and favorite. Each user can have multiple unique favorites.
table user u
[ user_id + name ]
100 | Sally
table favorite fav
[ fav_id + user_id + fav_key + fav_val ]
1 | 100 | icecream | mint
2 | 100 | candybar | snickers
3 | 100 | color | red
I want to create a SELECT statement that will turn the user's favorites into columns using the fav_key value as the column header. *The problem is I will never know what the fav_val value will be as these are user entered, so the column names have to be generated dynamically.
SELECT ...
[ user_id + name + fav_icecream + fav_candybar + fav_color ]
100 | Sally | mint | snickers | red
With some distant thought of performance in mind -- one of the issues is that I don't want to run two SELECT statements to get the user data and the user favorites (plus I like the idea of having the columns dynamically named in this way).
UPDATE
So this is called, pivoting, excellent.
What if I don't ever know what the values are? I need to dynamically generate the columns from a query on favorites.
Like this:
Select fav.user_id, u.name
MAX(case WHEN fav.fav_key = 'icecream' then fav.fav_val end) as 'fav_icecream',
MAX(case WHEN fav.fav_key = 'candybar' then fav.fav_val end) as 'fav_candybar',
MAX(case WHEN fav.fav_key = 'color' then fav.fav_val end) as 'fav_color'
From favorite fav
inner join users u on fav.user_id = u.user_id
group by fav.user_id
Working Example: DEMO
Note that: the demo is for MS SQL Server but it is working the same way for mysql, I just tried to give you a live demo.
Essentially you want PIVOT functionality. Unfortunately, that's not natively supported by MySQL (unlike Oracle or SQL Server). There are many questions on StackOverflow showing how to work around that lacking functionality of MySQL:
https://stackoverflow.com/search?q=mysql+pivot+sql
Some examples:
pivot in mysql queries
MySQL Query and Pivot Tables

Database Design: Multiple tables vs a single table

I am making a website where there are different types of items such as blogs, posts, articles and so on. A user can set any one of them as his/her favorite. Now when I approach this thing, I have two options
Make a table for user favorites for each type of object.
Make a common table for all type of objects for all the users.
The problem with the 1st structure is that I will have to query a lot of tables for displaying the favorites of a particular user. But it will allow me to easily group the favorites into different categories.
However if I have to show all the favorites on one single page and merge them all, sorted according to time, then that becomes difficult. But if I use the second model, I can easily get the latest favorites, and also grouping them according to object type is not difficult, but I will have one large table site wide.
Which of the two strategies will be more scalable.
The 1st one entails multiple database queries, and the second one
entails a large single table.
If it helps, I am using MySql
It seems that you already know the answer, but remember, keep the systems you design simple to modify as business models always change over time or they eventually fail (it's a generalization but you get the idea). A corollary of that is if you make a rigid model, fast or slow, it's rigid, changes will be harder and the end user won't see the difference, hence no money/happiness change is achieved, unless it's a very bad change.
Your problem is not technical in a way a query works on the engine but more of a philosophical one, easy changes versus apparent speed.
Ask yourself, what's the advantage of having a normalized database? Think about a clean architecture and design, performance is the least problem in todays world as processing is cheaper and storage also. But design is expensive.
Normalization was made to make systems that don't depend on last moment decisions but on a structured design process.
Big tables are not a big deal for MySql but they are a big deal to maintain, modify and expand. It's not just adding one more column, it's about the rigid structure of the data itself. Eventually in time you will just add columns that contain indexes, and those indexes will be pointing to small tables. MySql will be plowing it's way around all that data anyway.
So i'll go for the first one, a lot of small tables, many-to-many.
I have this design on my website. My modules are: news, articles, videos, photos, downloads, reviews, quizzes, polls, etc etc. All in separate tables. I have a likes table where users can like or dislike a post (in your case favorites). The query to get these isn't that complicated.
First off for the most part MOST of my tables for the modules are structured the same way:
id
title
content
user_id (author)
date
etc
with a few exceptions being that sometimes title is called question or there is no content column. That does not cause any issues.
My likes tables is set up like this:
id
page_id
module_id (what table did it come from...I have a modules table where each module has a title, associated id, directory, etc)
post_id (corresponds to the module table id)
user_id (user who did the liking or posting)
status (0 = like, 1 = dislike)
date (when the liking/disliking took place)
Modules table example:
id
title
directory
post_type
Example
id title directory post_type
1 News news news
2 Episode Guide episodes episode
3 Albums discography/albums album
Essentially yours would have a similar set up, modifying the table structure as necessary for your needs.
Query to get all the likes or favorites for a particular user:
$getlikes = mysql_query("SELECT DISTINCT post_id, module_id, page_id FROM likes WHERE user_id = $profile_id ORDER BY id DESC LIMIT $offset, $likes_limit", $conn);
$likes = mysql_num_rows($getlikes);
if($likes == "0"){
echo "<br><Center>$profile_username does not have any liked posts at this time.</center><BR>";
}
else {
echo "<table width='100%' cellspacing='0' cellpadding='5'>
<Tr><th>Post</th><th align='center'>Module</th><th align='center'>Page</th><tr>";
while ($rowlikes = mysql_fetch_assoc($getlikes)) {
// echo data
$like_page_id = $rowlikes['page_id'];
$like_module_id = $rowlikes['module_id'];
$like_post_id = $rowlikes['post_id'];
// different modules have different fields for the "title", most are called title but quotes is called "content" and polls is called "questions"
if($like_module_id == "11"){
$field = "question";
}
elseif($like_module_id == "19"){
$field = "content";
}
else{
$field = "title";
}
// FUNCTIONS
PostURL($like_page_id, $like_module_id, $like_post_id);
ModTitle($like_module_id);
ModTable($like_module_id);
ModURL($like_page_id, $like_module_id);
fpgURL($like_page_id);
$getpostinfo = mysql_query("SELECT $field AS field FROM $mod_table WHERE id = $like_post_id", $conn);
$rowpostinfo = mysql_fetch_assoc($getpostinfo);
$like_post_title = $rowpostinfo['field'];
// Using my "tiny" function to shorten the title if the module is "Quotes"
if($like_module_id == "19"){
Tiny($like_post_title, "75");
$like_post_title = "\"$tiny\"";
}
if(!$like_post_title){
$like_post_title = "<i>Unknown</i>";
}
else {
$like_post_title = "<a href='$post_url'>$like_post_title</a>";
}
echo "<tr class='$altrow'>
<td>$like_post_title</td>
<td align='center'><a href='$mod_url'>$mod_title</a></td>
<td align='center'>$fpg_url</td>
</tr>";
$altrow = ($altrow == 'altrow')?'':'altrow';
} // end while
echo "<tr><Td align='center' colspan='3'>";
// FUNCTIONS - Pagination links
PaginationLinks("$cs_url/users/$profile_id", "likes");
echo "</td></tr></table>";
} // end else if no likes
Ok that may be hard for you to understand since I have alot of my own variables, but basically it gets the module id and post id from the likes table and then runs a query to get the title of the post and any other info I want like the original author.
I have "module" functions set up that will return the url or the title of the module given you provide an id for it.
So if I'm not mistaken, you are trying to create a Favorites table to collect the user's favorite items right? If so, you will need at least two tables.
Types: The types of the resources.
+----+---------+
| ID | Name |
+----+---------+
| 0 | blog |
| 1 | post |
| 2 | article |
| 3 | photo |
| 4 | video |
+----+---------+
Favorites: The most important part of the Favorite system, it's kinda like a relationships map.
+--------+----------+--------------+
| UserID | TargetID | TargetTypeID |
+--------+----------+--------------+
| 941 | 1 | 0 |
| 6 | 935 | 1 |
| 26 | 51 | 4 |
| 7 | 87 | 2 |
+--------+----------+--------------+
Posts: The example posts table, you might also have Blogs or Photos and Albums tables.
+-----+------------------+
| ID | Title |
+-----+------------------+
| 0 | This is my post! |
| 51 | Oh, how are you? |
| 935 | Hello, world! |
+-----+------------------+
Now, the SQL Query might be like this (untested):
-- Get the posts
SELECT p.*
FROM Posts p
LEFT JOIN Favorites f
-- Which are favorited by the user 6
ON f.UserID = 6
-- Also get the type id of the `post`,
-- so we can specify the favorite type of the favorite items
AND f.TargetTypeID = (
SELECT ID
FROM Types
WHERE Name = 'post'
)
-- Make sure we only get the posts which are favorited by the user.
WHERE p.ID = f.TargetID
With the SQL Query above, you can get the favorite posts which is been favorited by the User ID 6.
+-----+------------------+
| ID | Title |
+-----+------------------+
| 935 | Hello, world! |
+-----+------------------+