Limit identical input in database to a certain count - mysql

I know that we can limit an identical input in database to only one by the keyword UNIQUE, but how about limiting it to more than one? For example, 3,4? Is there a way to achieve this?

The only way is to do it on your way by checking that amount before doing a new insert.
Before insert a new row, check how many identical rows there are and handle that case (e.g. don't perform the insert and/or show a message to the user).

Related

MySQL - checking max rows during insert

We have a table where we limit the number of rows per user to a certain number. Before insert, we check if user has exceeded the storage capacity (number of rows) and then insert as appropriate. For example,
select count(id) from items where user=123;
say, if count < 10,
insert into items set user=123, a=xyx;
However, this approach requires two queries. Is there a way in which is can be done in a single query.
Thanks
Pretty much any approach you take will require two queries. Whether you do this in a trigger or in application code is a matter of choice.
If you use your method, then add an index on items(user). This will make it cheap to count the number of rows.
An alternative is to increment a value in the user table for each item. So, when a user inserts an item, then increment users.itemcount. Remember, though, to reduce the count when you delete items.
If you just want to have 1 query in a code you can try to use conditional insert with approach described here MySQL Conditional Insert

best way to get the last inserted record in sql server

Hi all I having a Identity column and a Computed primary key column in my table I need to get the last inserted record immediately after inserting the record in to database, So I have written the following queries can some one tell which is the best one to choose
SELECT
t.[StudentID]
FROM
[tbl_Student] t
WHERE
t.ID = IDENT_CURRENT('tbl_Student')
The other is using MAX as follows
Select
MAX(StudentID)
from tbl_Student
From the above two queries which is the best one to choose.
MAX and IDENT_CURRENT, according to technet, would behave much the same and both would be equally unreliable.
"IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns the identity value generated for a specific table in any session and any scope. For more information, see IDENT_CURRENT (Transact-SQL)."
Basically, to return the last insert within the current scope, regardless of any potential triggers or inserts / deletes from other sessions, you should use SCOPE_IDENTITY. Of course, that's assuming you're running the query in the same scope as the actual insert in the first place. :)
If you are, you also have the alternative of simply using OUTPUT clause to get the inserted ID values into a table variable / temporary table, and select from there.
The original answer, where my assumptions about IDENT_CURRENTwhere wrong.
Use the first one. IDENT_CURRENT should give you the last item for the current connection. If someone else would insert another student concurrently IDENT_CURRENT will give you the correct value for both clients, while MAX might give you a wrong value.
EDIT:
As it was mentioned in the other answer IDENT_CURRENTand MAXare equally unreliable in case of concurrent usage. I would still go for IDENT_CURRENT but if you want to get the last identity used by the current scope or session you can use the functions ##IDENTITY and SCOPE_IDENTITY. This technet article explains the detailed differences between IDENT_CURRENT, ##IDENTITY and SCOPE_IDENTITY.

Insert random number into table upon new record creation

I would like to store random numbers in one MySql table, randomly retrieve one and insert it into another table column each time a new record is created. I want to delete the retrieved number from the random number table as it is used.
The random numbers are 3 digit, there are 900 of them.
I have read several posts here that describe the problems using unique random numbers and triggering their insertion. I want to use this method as it seems to be reliable while generating few problems.
Can anyone here give me an example of a sql query that will accomplish the above? (If sql query is not the recommended way to do this please feel free to recommend a better method.)
Thank you for any help you can give.
I put together the two suggestions here and tried this trigger and query:
CREATE TRIGGER rand_num before
INSERT ON uau3h_users FOR EACH ROW
insert into uau3h_users (member_number)
select random_number from uau3h_rand900
where random_number not in (select member_number from uau3h_users)
order by random_number
limit 1
But it seems that there is already a trigger attached to that table so the new one cause a conflict, things stopped working until I removed it. Any ideas about how accomplish the same using another method?
You are only dealing with 900 records, so performance is not a major issue.
If you are doing a single insert into a table, you can do something like the following:
insert into t(rand)
select rand
from rand900
where rand not in (select rand from t)
order by rand()
limit 1
In other words, you don't have to continually delete from one table and move to the other. You can just choose to insert values that don't already exist. If performance is a concern, then indexes will help in this case.
More than likely you need to take a look into Triggers. You can do some stuff for instance after inserting a record in a table. Refer this link to more details.
http://dev.mysql.com/doc/refman/5.0/en/create-trigger.html

mysql prevent insert row auto sorting

I use Codeigniter to perform insert to mysql (not sure if relevant), I have table column and some data like this after I insert:
[invoice_id][product_id][unit_cost][quantity]
[42][1][50][2]
[42][2][100][3]
[42][5][45][1]
The problem is mysql auto sort it by invoice_id first then product_id like the above.
Before I insert them, my invoice item-list position was :
[42][5][45][1]
[42][1][50][2]
[42][2][100][3]
I do not want any of this auto-sort because when I retrieve them, they went like the list in database not as in the invoice. I dont think I can use sort for a particular column because they are all random in the first place.
I can only start thinking to add another column [position] contain number just for the sake of sorting it later, or is there a better way without it?
Thanks in advance for any reply.
You are not guaranteed the order of MySql resultsets unless you specify an ORDER BY clause. The only way to do it if you cannot sort with the parameters you already have would be to add another column to the table. Typically this would be an autoincrement integer field. You would then be able to order by id, and return the rows in the order they were entered.

storing records in mysql db in sorting order of date

I want to store some records in mysql database. records have a date column. i want to store them in sorting order of that date column.
For example, record having date 27/sep/2011 get stored as first row on the top of record having date 26/sep/2011 as:
id_1,name_1,27/sep/2011
id_2,name_2,26/sep/2011
if new records come on future dates they would get inserted on the top.
I DONT want to order them while using select by using order by desc .
i want they get inserted into db directly in sorted order.
how to do this???
thanks...
I am always surprised when people want to determine physical order of storing records.
Basically, it's a terrible idea for multiple reasons.
1) How the record is physically stored should not be of your concern.
2) How the record is presented should be of your concern. That's why we have ORDER BY built in.
3) Determining physical storage should be done by experts in the field, since it has performance implications - which is a topic in its own and I won't go into details.
Basically, worry about getting the data out in the sorted order, not getting it in in the sorted order.
Reason why it's a bad idea is because you'll be tampering with the primary key which is never, ever a good idea. On top of that, you'll have to reorder the records every time you insert something. Just don't reinvent hot water.
You could do this by adding another table - inserting all of the records into that table (the current and the new ones) then doing and insert as follows :
INSERT into newtable
select * from temptable
order by temptable.date
Why do you need to do this ? why not just use orderby on the query ?
As pointed out in the comments below - you would need to truncate the newtable each time
You cannot choose where to insert your row.
Here's one possible solution: MySQL syntax for inserting a new row in middle rows?