Generating a unique MySQL field based on the contents of other fields - mysql

In creating unique custom reference codes (i.e. JOB1293XYZ) for a while I have been generating custom reference/hashes in PHP then checking my database to see if it already exists and if so generating another.
I'm curious if in MySQL it is possible to to generate the contents of a field based on the other fields in that row, i would be a handy shortcut. For Example...
Table: Employees
employeeId
firstName
lastName
jobTitle
DOB
employeeCode
So for employeeCode can I perhaps use a MySQL Custom Function (which I know very little about) to generate the contents of the field. perhaps by taking the first letter of the firstname, first letter of the second name, the str length of the job title and the last two digits of the DOB? This is purely an example.
If this is possible and anyone can point me to any reference material that would be great, have been wading through the heavy MySQL documentation and will continue to do so for the time being.
Thanks in advance!

You could concatenate all of the fields together and do an MD5 on the resulting string.
UPDATE Employees SET md5str=MD5(CONCAT(field1, field2, field3))...
I wouldn't recommend this approach because then the question of what to do if you had a hash collision would be very difficult if not impossible to answer.
The above idea is not mine: I spotted this in the maatkit code.

Related

How Can I Check A String Whether It Does Exists In A The Given String Or Does Not?

I am currently working on a database project that uses platform MySQL. Project includes tables such as course, instructor, researchArea etc. What I really need is a trigger that checks how many words from "researchArea keywords" are in the given text. Text is going to be pulled from another table which named course. With the result I am planing to get a integer matching percentage value and with the value, I planned to insert the calculated value into "matchingvalue" which is a attribute in instructor table, a attribute to describe the relation of the course content between the instructor.
I have a big lack of scripting experience and syntax information in sql already and I couldn't even think a solution to solve this thing. Any ideas to create a trigger for this query or function whatever it is?
Image of the EER

Access: DMax and String ID

Because the developers of the Oracle database we use are hell-bent on making my life difficult :), they decided to use numbers for the PK for some tables and VARCHAR for the PK for other tables.
For the Access front-end I'm building, I have a form with a textbox which I want to display the last ID used on a table + 1 (so if the last ID was 100, then 101 would display in the box). Naturally, the table I need to do this on as a VARCHAR ID, even though all of the IDs are sequential numbers. Converting the field to numeric, while would fix my purpose, is not going to happen.
So, my question: in my other textbox where the ID is numeric, I am able to use DMAX to find the last number used; however, this isn't working for the string ID. I've read about using the Val() function to convert the string to text, but I can't figure out how to use both. I tried the following:
DMax(Val("[EAUSER_INFORMATION_ITEM]![INFORMATION_ITEM_ID]"),[EAUSER_INFORMATION_ITEM],"")
but this comes back with a #Name? error.
Would someone point me in the right direction?
Thanks!
You should use Val inside of the quotes, not outside of them, else you get this problem. Also, all arguments inside of a domain aggregates need to be strings:
DMax("Val([INFORMATION_ITEM_ID])","[EAUSER_INFORMATION_ITEM]")
You can omit the last argument, the WHERE condition, if you're not using it, and you don't need to specify the tablename if there's only one table.
You probably can't do anything about it, but using ascending numeric strings as primary keys is a major bad practice. Most database engines will sort in ascending order, causing massive fragmentation (because "100" < "2" is True)

Adding a new record to a relationship in MySQL

I'm trying to learn more about creating "advanced" databases, so my project is to keep track of the wins and losses at a website called SaltyBet. Bots fight against each other and people bet on the outcome. I want to create a database for myself to keep track of each match, where I enter in the values manually.
I have 2 tables:
chars with just an "ID" field and a "name" (unique) field, and
matches with "ID", "player1", "player2", "winner", and "odds".
The way I want it to work is if I go to insert a row into matches, it will create the appropriate character in the chars database, if it doesn't already exist.
I have the following relationships set up within PHPMyAdmin:
Creating this form in the "Insert" view:
This works fine - as long as I have already entered in both characters in the chars table. However, there often isn't enough time to go through 3 different views to create the appropriate characters in the chars table to then use in the matches table. I had the idea to create a trigger, which inserts the characters if they don't exist, but AFAIK I cannot maintain the relationship between the two tables because I cannot enter a new one in matches.
Is there any way I can easily approach this without writing a form in PHP? I'd rather learn how to do it the "proper" way instead of relying on the simple MySQL commands I learned years ago and never expanded on.
Thank you!
I agree that if you want to use a trigger that creates the row in chars after an insert in matches, it won't work because the insert itself will give a problem.
I don't see how you can do it without coding an application that would first verify in chars whether the row exists, insert it if needed, then insert into matches.

MySQL 5.5 Database design. Problem with friendly URLs approach

I have a maybe stupid question but I need to ask it :-)
My Friendly URL (furl) database design approach is fairly summarized in the following diagram (InnoDB at MySQL 5.5 used)
Each item will generate as many furls as languages available on the website. The furl_redirect table represents the controller path for each item. I show you an example:
item.id = 1000
item.title = 'Example title'
furl_redirect = 'item/1000'
furl.url = 'en/example-title-1000'
furl.url = 'es/example-title-1000'
furl.url = 'it/example-title-1000'
When you insert a new item, its furl_redirect and furls must be also inserted. The problem appears becouse of the (necessary) unique constraint in the furl table. As you see above, in order to get unique urls, I use the title of the item (it is not necessarily unique) + the id to create the unique url. That means the order of inserting rows should be as follow:
1. Insert item -- (and get the id of the new item inserted) ERROR!! furl_redirect_id must not be null!!
2. Insert furl_redirect -- (need the item id to create de path)
3. Insert furl -- (need the item id to create de url)
I would like an elegant solution to this problem, but I can not get it!
Is there a way of getting the next AutoIncrement value on an InnoDB Table?, and is it recommended to use it?
Can you think of another way to ensure the uniqueness of the friendly urls that is independent of the items' id? Am I missing something crucial?
Any solution is welcome!
Thanks!
You can get an auto-increment in InnoDB, see here. Whether you should use it or not depends on what kind of throughput you need and can achieve. Any auto-increment/identity type column, when used as a primary key, can create a "hot spot" which can limit performance.
Another option would be to use an alphanumeric ID, like bit.ly or other URL shorteners. The advantage of these is that you can have short IDs that use base 36 (a-z+0-9) instead of base 10. Why is this important? Because you can use a random number generator to pick a number out of a fairly big domain - 6 characters gets you 2 billion combinations. You convert the number to base 36, and then check to see if you already have this number assigned. If not, you have your new ID and off you go, otherwise generate a new random number. This helps to avoid hotspots if that turns out to be necessary for your system. Auto-increment is easier and I'd try that first to see if it works under the loads that you're anticipating.
You could also use the base 36 ID and the auto-increment together so that your friendly URLs are shorter, which is often the point.
You might consider another ways to deal with your project.
At first, you are using "en/" "de/" etc, for changing language. May I ask how does it work in script? If you have different folders for different languages your script and users must suffer a lot. Try to use gettext or any other localisation method (depends on size of your project).
About the friendly url's. My favorite method is to have only one extra column in item's table. For example:
Table picture
id, path, title, alias, created
Values:
1, uploads/pics/mypicture.jpg, Great holidays, great-holidays, 2011-11-11 11:11:11
2, uploads/pics/anotherpic.jpg, Great holidays, great-holidays-1, 2011-12-12 12:12:12
Now in the script, while inserting the item, create alias from title, check if the alias exists already and if does, you can add id, random number, or count (depending on how many same titles u have already).
After you store the alais like this its very simple. User try to access
http://www.mywebsite.com/picture/great-holidays
So in your script you just see that user want to see picture, and picture with alias great-holidays. Find it in DB and show it.

Store a number of data fields in MySQL when you don't know what it will be

I wonder if anyone could offer their advice on this one.
I have some customer data whereby certain fields remain consistent. For example:
'Firstname', 'Lastname', 'Postcode'
These are the important fields and the ones that would be searched against. Over time we may have some additional data for a customer, however it is guaranteed that the fields will differ, therefore we can't indefinitely create more fields in the table to accommodate every possible new field.
I wondered what the options would be of storing the auxiliary date fields, for example would creating one additional field 'AuxData' maybe as a VARCHAR that used a JSON array?
(I am thinking of what I have seen in wordpress in the past)
I'd really appreciate anyone's thoughts on this one!
Many thanks
JAson
You can create an extra column with XML data, usually I would recommend JSON over XML, but MySQL has some special functionality to search trough XML data in fields. See this article for a few examples: http://www.informit.com/articles/article.aspx?p=1019623
There is also another possibility, you could create a new table with 3 columns: [Person_ID, Property, Value] where the primary key would span (Person_ID, Property). This way you can more easily search trough data, and you keep it MySQL instead of XML/JSON. However both options are valid.