This question already has answers here:
mysql unique number generation
(9 answers)
Closed 8 years ago.
I am wondering if there is any way to generate the random five digit number and insert into database using mysql. I know i can do it using PHP but wanted to know if i can get rid of the php and do it using database. Also, the generated number should be different than the numbers already stored in the database.
Following is example as how it should look like:
I have four letters of pattern common in random_no field which is org1 and want to append other 5 random letters as shown in following example:
+-------+-----------+-----------+--------------------------------------------+
| id | title | phone | ABN | Random No |
+-------+-----------+----------+---------------------------------------------
| 1 | title1 | 4765 5678 | 214-444-1234 | org123456 |
| 2 | title2 | 4444 4444 | 555-111-1234 | org109876 |
| 3 | title3 | 3333 3333 | 214-222-1234 | org187654 |
| 4 | title4 | 1111 1111 | 817-333-1234 | org156432 |
| 5 | title5 | 2222 2222 | 214-555-1234 | org177654 |
+-------+-----------+-----------+--------------------------------------------
Any help will be appreciated.
Now there is no guarentee that there are not going to be duplicates... but this is getting two random numbers and multiplying them by different numbers so its not all that likely that they will be getting random numbers
UPDATE table t,
( SELECT id, LPAD(FLOOR(7 + (RAND() * 50) * (RAND() * 333)), 5, 0) as join_num
FROM table
)t1
SET t.random_no = CONCAT(t.random_no, t1.join_num)
WHERE t.id = t1.id;
From here I recommend you do this.. after updating your table go back through and run this query
SELECT id FROM table
GROUP BY random_no
HAVING COUNT(*) > 1;
if there are any results returned then the id's there will need a different random number and you can just change it at any duplicate spots once you know if there are any dupes
Breakdown of the update query....
update the table alias t.
select from table the id and then the random number alias t1.
concat the number and the column by row..
where the id's are equal... getting a different number for each row.
LPAD is a zero fill so that way if the number is smaller than 5 spaces it'll fill it in with 0's and then you have to use FLOOR() with RAND() for the random number.
Hope thats helpful!
Related
This question already has answers here:
MySQL query finding values in a comma separated string
(11 answers)
Closed 6 years ago.
I have a table named 'offers' that has a column in_stores. It contains the ids of the stores that this offer is available in. Graphically this table looks like this:
id | title | in_stores
1 | Shoes | 1002,1003
2 | Gloves | 1020,1011
3 | Shades | 1002,1009
4 | Hats | 1010,1002
5 | Shoes | 1220
6 | Shirts | 1010
7 | Hats | 1002
Each value in in_stores is saved with the implode() function through PHP.
My question:
How to select in a single mysqli query all the offers that are available in a store with id 1002. In this example the query should return offers with id 1,3,4,7. I guess I should use something like explode() first to get the results in an array and than in_array() to search for the specific id in it but all those functions are unavailable within SQL.
This is a major issue with storing comma separated fields.
MySQL does have a function to allow searching for these, and this will be a lot more reliable than trying to rely on using LIKE. But as it still cannot effectively use any index it will not be fast.
SELECT *
FROM offers
WHERE FIND_IN_SET('1002', in_stores)
Far better to redesign your database to use an extra table with a row for each value for each id.
You "could" do it with a LIKE Query, but this is not recommended.
SELECT * FROM offers WHERE in_stores LIKE "%1002%".
As long as you don't have values bigger than 9999 this will work.
BUT when one of your stores has the id 11002 of 99991002 it will also return these unwanted values.
What you should do is transform your mysql table to a have a second table storeLocations or sth. else. This should only have the properties offer_id and store_id.
It will transform your data to:
`offers`
id | title
1 | Shoes
2 | Gloves
3 | Shades
4 | Hats
5 | Shoes
6 | Shirts
7 | Hats
`storeLocations`
offer_id, store_id
1 | 1002
1 | 1003
2 | 1020
2 | 1011
3 | 1002
3 | 1009
4 | 1010
4 | 1002
5 | 1220
6 | 1010
7 | 1002
Then you can select from it like
SELECT * FROM offers AS o
LEFT JOIN storeLocations as l ON (o.id=l.offer_id)
WHERE l.store_id = 1002;
Now when you insert data you don't have to use implode but insert as many rows into storeLocations as there are store_id's for that specific item.
For more info on that topic have a look here.
I think you should be using the MySQL LIKE operator. It searches the database column for strings specified in your query.
Try this query:
$sql = "SELECT * FROM offers WHERE in_store LIKE '%1002%'";
Check this link for more explanation: W3Schools - SQL LIKE Operator
I think that should do the trick.
Right now I have a PHP script that is fetching the first three results from a MYSQL database using:
SELECT * FROM table Order by DATE DESC LIMIT 3;
After that command I wanted PHP to fetch the next three results, initially I was going to use:
SELECT * FROM table Order by DATE DESC LIMIT 3,3;
However there will be a delay between the two commands which means that it is very possible that a new row will be inserted into the table during the delay. My first thought was to store the DATE value of the last result and then include a WHERE DATE > $stored_date but if entry 3 and 4 have the same date it will skip entry 4 and return results from 5 onward. This could be avoided using the primary key field which is an integer which increments automatically.
I am not sure which the best approach is, but I feel like there should be a more elegant and robust solution to this problem, however I am struggling to think of it.
Example table:
-------------------------------------------
| PrimaryKey | Data | Date |
-------------------------------------------
| 0 | abc | 2014-06-17 11:43:00 |
| 1 | def | 2014-06-17 12:43:00 |
| 2 | ghi | 2014-06-17 13:43:00 |
| 3 | jkl | 2014-06-17 13:56:00 |
| 4 | mno | 2014-06-17 14:23:00 |
| 5 | pqr | 2014-06-17 14:43:00 |
| 6 | stu | 2014-06-17 15:43:00 |
-------------------------------------------
Where Data is the column that I want.
Best will be using primary key and select like
SELECT * FROM table WHERE pk < $stored_pk Order by DATE DESC LIMIT 3;
And if you have automatically generated PK you should use ORDER BY pk it will be faster
Two options I can think of depending on what your script does:
You could either use transactions: performing these queries inside a transaction will give you a consistent view of the data.
Alternatively you could just use:
SELECT * FROM table Order by DATE DESC;
And only fetch the results as you need them.
Looking for a solution to keep a random order of a user table in the database when clicking the next page button.
Actually I have a database with 1000 users and I want to display 10 users each page (in a memberlist), my query looks like this:
$sql = "SELECT * FROM users ORDER BY user_id LIMIT 1,10";
Now I would like to ORDER BY RAND() and it works, except of course when clicking the next page, then it is shuffled again and it happens sometimes that the same users will be there again.
So my question is about a solution to keep the random order I had on the first page, also on the next pages.
I thought about to set a $_SESSION variable when someone visits the memberlist for the first time with shuffled numbers from 1 to 1000 in it and then order the members by position in the $_SESSION variable where a number is equal to a user_id.
Don't know how this might be possible, but I actually imagine a solution like:
$numbers = range(1, 1000);
$shuffled_numbers = shuffle($numbers);
$sort = $_SESSION['random_user_sort'] = $shuffled_numbers;
So I will have a mysql query when clicking page two (next page) like this:
$sql = "SELECT * FROM users ORDER BY $sort LIMIT 11,20";
Any solution to let it work this way or even better ideas?
The RAND() function does not really generate random numbers but what's called pseudo random numbers: numbers are calculated with a deterministic formula and they're just intended to look random. To calculate a new number, you take the previous one and apply the formula to it, and that's how we get different output with a deterministic function: by using different input.
The initial number we use is known as seed. If you have a look at the manual you'll see that RAND() has an optional argument:
RAND(), RAND(N)
Returns a random floating-point value v in the range 0 <= v < 1.0. If
a constant integer argument N is specified, it is used as the seed
value, which produces a repeatable sequence of column values
You've probably figured out by now where I want to go:
mysql> SELECT language_id, name FROM language ORDER BY RAND(33);
+-------------+----------+
| language_id | name |
+-------------+----------+
| 3 | Japanese |
| 1 | English |
| 4 | Mandarin |
| 6 | German |
| 5 | French |
| 2 | Italian |
+-------------+----------+
6 rows in set (0.00 sec)
mysql> SELECT language_id, name FROM language ORDER BY RAND(33);
+-------------+----------+
| language_id | name |
+-------------+----------+
| 3 | Japanese |
| 1 | English |
| 4 | Mandarin |
| 6 | German |
| 5 | French |
| 2 | Italian |
+-------------+----------+
6 rows in set (0.00 sec)
P.S. The manual is not explicit about the seed range (it just says integer), you might need some extra research (or just some quick testing).
I am trying to generate fixtures for a sports website. I have a table called Members, with relevant columns being member_id and league_id. The league_id will be passed from a form on the previous page as the variable $leagueid.
I'm pulling out all the member ID's relating to that league ID using...
$result = mysql_query("SELECT member_id FROM Members WHERE league_id = '$leagueid'")
I now need to generate fixtures for all these member ID's and then insert that data into the MySQL table 'Fixtures'. Each row of data in that table needs to include:-
player1 - member_id of the first player
player2 - member_id of the second player
week - integer showing which week the match will be played
league_id
However, there are some special conditions that also need to be applied.
Every 3rd week needs to remain free (i.e. weeks 3,6,9,12 etc). No matches can be scheduled on these weeks
There needs to be an option (which will be selected and passed from a form on the previous page as a checkbox variable called $double) which will double up the matches. This means that after generating one complete round of fixtures, you need to take the generated list, swap ID's for players 1 and 2, and duplicate them all. So 1 round of fixtures could look like this....
Week 1
1 vs 2
3 vs 4
Week 2
1 vs 3
2 vs 4
Week 3
1 vs 4
2 vs 3
Then you would swap the ID's and add on another set...
Week 4
2 vs 1
4 vs 3
Week 5
3 vs 1
4 vs 2
Week 6
4 vs 1
3 vs 2
What I'm looking for is some code that will generate all these fixtures while keeping in mind all the special conditions that I've listed.
I know this is all possible in PHP but I also think I can do it using one SQL query instead, which might be a lot cleaner. Can anyone help me out?? Thanks!!
P.S. I know I'm using mysql and not mysqli. I am currently trying to transfer over to mysqli but I'm having some problems which I have posted on a separate question that I have yet to get a correct answer to.
SELECT * FROM ints;
+---+
| i |
+---+
| 0 |
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 6 |
| 7 |
| 8 |
| 9 |
+---+
SELECT * FROM ints WHERE MOD(i,3) > 0;
+---+
| i |
+---+
| 1 |
| 2 |
| 4 |
| 5 |
| 7 |
| 8 |
+---+
The second part is simply
INSERT INTO my_table SELECT week_id+3, column_2, column_1 FROM my_table;
I have what might be a simple question but I can't seem to figure out how to do it. I am trying to write a query that counts the number of unique results per query and stores both the values and the number of times it was a query result to a different database.
Here's an example of what I am basically trying to do...
Say I have a table 'color'
+------------+------------+------------+
| id | color | letter |
+------------+------------+------------+
| 1 | blue | a |
| 2 | blue | b |
| 3 | red | a |
| 4 | red | b |
| 5 | green | a |
+------------+------------+------------+
I have a query that will run multiple times using this table
to find the corresponding letter and color:
$query = ("SELECT * FROM colors WHERE letter = '$someletter'");
$query1 = mysql_query($query);
while($row = mysql_fetch_array($query1)) {
$id = $row['id'];
$color = $row['color'];
};
For each query I am writing the $id and $color variables to a seperate log file.
For example, using the above query, $someletter = "a". (call this query #1)
The results would be:
+------------+------------+------------+
| id | color | letter |
+------------+------------+------------+
| 1 | blue | a |
| 3 | red | a |
| 5 | green | a |
+------------+------------+------------+
Blue, red, and green would have one result each.
If the query was run with $someletter = "b" (call this query #2)
The result set would be:
+------------+------------+------------+
| id | color | letter |
+------------+------------+------------+
| 2 | blue | b |
| 4 | red | b |
+------------+------------+------------+
Blue and red would each get one result.
So the total number of results for both queries #1 and #2:
+------------+------------+------------+
| id | color | totalresult|
+------------+------------+------------+
| 1 | blue | 2 |
| 3 | red | 2 |
| 5 | green | 1 |
+------------+------------+------------+
Basically, I want to figure out a way to get a count of all the unique results for X number of queries. Because this query will be run multiple times with different variables, I would like to store the results in a database that could have a column for color and a column for total results as I have shown above. Also, I am just using the table 'color' as an example and the actual number of unique entries would be in the hundreds, so the query would have to work for that.
I was thinking of some form of COUNT or GROUP but I cant seem to connect the dots.
Any help would be much appreciated.
$query = 'SELECT color, COUNT(letter) totalresult FROM colors GROUP BY color';
That should give you the colors and the number of times it appears (per color). I've left out the id column, because you can't map a row to a single id so that information is useless.
Update
In order to store the search results you could create two tables. The first (search_query) only needs to contain an id and a varchar column to hold the query. You could add a timestamp also to find out when people use the search option.
The second table (search_results) contains one result per row. It consists of a foreign key to the first table, and the result. Instead of a complete result you also could log the id of the result row. (So if someone searches for the letter b you only would need to log color ids 2 and 4. That means you need two rows in the search_results table.)
If the search results could come from more than one table, you would need to add the table name to the search results table too. I would just use a varchar column for that.
what you want to use is mysql_num_rows($query1); this returns the number of rows in the result.
select color, count(id) from color group by color
I believe you will need 2 database accesses - one to retrieve the current total, and one to update it with the new total.