MySQL search / random row - php

Hopefully i can explain this well enough!..
I want to search a MySQL table for certain keywords, cool no problem i can do that..
However.. I want to return just 1 random row based upon a good match of these keywords.
What would be the best way to do this if i had a table with thousands of rows and keep everything super fast.
First to mind would be to return an array of 10 random rows loop over them and check for keywords in PHP and get this run over till a good match has been found then stop.. so if in them first 10 a match wasn't found it will query the database again..
Any help is most appreciated!

SELECT * FROM table WHERE search="word" ORDER BY RAND() LIMIT 1;

Related

PHP, indexing mysql ID in json. Is it worth it?

I have a database in which i've got a table where im having question to be displayed randomly on the main site (about 80 for now). Im reading all the IDs from the database and then randomly selecting one and doing next query to get all the rest needed data of this one. And im curious if should i leave this like that or would it be bether to store all the IDs in .json file and just update it every time i add a question. What is bether? Thanks for help.
If you're just interested in a random record from the table, just do it like this:
SELECT * FROM your_table
ORDER BY RAND()
LIMIT 1;
All in one query and you don't have to retrieve a list of IDs first.
And it's almost always a bad idea to maintain two separate data sources.

PHP/MySQL - Show user the number of results their query had, even if you are limiting the number displayed?

Apologies if I am not wording this correctly but what I have at the moment is a search form and the user can type in how many results they want to be returned but what I would like to do is also show the user the total number of matches in the database.
e.g. User selects their search criteria with a limit of 10 but there are 50 matches in the database.
I would like to tell the user is that there are 50 possible results.
One thing I am not sure of is if this can be combined with my existing query or if a separate query will have to be submitted?
The PHP code to generate my queries is quite complicated but if you would like me to post it just let me know.
Thanks.
Have a look at the SQL_CALC_FOUND_ROWS option for mysql.
http://dev.mysql.com/doc/refman/5.1/en/information-functions.html#function_found-rows
And yes, you'll need a second query like:
SELECT FOUND_ROWS()
To get the "real" number of 'would have been' results.

How to order results of a query randomly & select random rows. (MySQL)

Please note I am a beginner to this.
I have two questions:
1) How can I order the results of a query randomly.
example query:
$get_questions = mysql_query("SELECT * FROM item_bank_tb WHERE item_type=1 OR item_type=3 OR item_type=4");
2) The best method to select random rows from a table. So lets say I want to grab 10 rows at random from a table.
Many thanks,
If you don't mind sacrificing complexity on the insert/update/delete operations for speed on the select, you can always add a sequence number and make sure it's maintained on insert/update/delete, then whenever you do a select, simply select on one or more random numbers from within this range. If the "sequence" column is indexed, I think that's about as fast as you'll get.
An alternative is "shuffling". Add a sequence column, insert random values into this column, and whenever you select records, order by the sequence column and update the selected record sequences to new random values. The update should only affect the records you've retrieved, so shouldn't be too costly ... but it may be worth running some tests against your dataset.
This may be a fairly evil thing to say, but I'll say it anyway ... is there ever a need to display 'random' data? if you're trying to display random records, you may be doing something wrong.
Think about Amazon ... do they display random products, or do they display popular ones, and 'things other people bought when they looked at this'. Does SO give you a list of random questions to the right of here, or a list of related ones? Just some food for thought.
SELECT * FROM item_bank_tb WHERE item_type in(1,3,4) order by rand() limit 10
Beware that order by rand() is very slow on large recordset.
EDIT. Take a look at this very interesting article that presents a different approach.
http://explainextended.com/2009/03/01/selecting-random-rows/

Optimal solution for next/previous function in PHP/mySQL

I want a good solution for next and previous in a php script. The first thing Im think is that you do this when you go next:
select id from table where id > '$_GET[id]' limit 1;
But how can I figure out if Im on first or last record? I want to hide next button if its the last record etc. Then Im think something like this:
select id from table where id > '$_GET[id]' limit 2;
if(mysql_num_rows($q) != 1) echo $nextButton;
The problem with my solution here is when Im on the first record! How can I possible how many record I have over the one Im selecting? Is there a simple and good solution for this or must I use more than one query to find out?
You actually need to find the number of pages based on the number of rows per page you're displaying. This will help you calculate an offset to feed into your LIMIT clause.
You can find a tutorial here
As a side note:
Do NOT pass $_GET['id'] into your SQL query the way you are. You must at least run mysql_real_escape_string() against it first.

MySql & PHP: How to find which row has an item in the leading spot in a CSV list?

This is kind of a weird question so my title is just as weird.
This is a voting app so I have a table called ballots that has a two important fields: username and ballot. The field ballot is a VARCHAR but it basically stores a list of 25 ids (numbers from 1-200) as CSVs. For example it might be:
22,12,1,3,4,5,6,7,...
And another one might have
3,4,12,1,4,5,...
And so on.
So given an id (let's say 12) I want to find which row (or username) has that id in the leading spot. So in our example above it would be the first user because he has 12 in the second position whereas the second user has it in the third position. It's possible that multiple people may have 12 in the leading position (say if user #3 and #4 have it in spot #1) and it's possible that no one may have ranked 12.
I also need to do the reverse (who has it in the worst spot) but I figure if I can figure out one problem the rest is easy.
I would like to do this using a minimal number of queries and statements but for the life of me I cannot see how.
The simplest solution I thought of is to traverse all of the users in the table and keep track of who has an id in the leading spot. This will work fine for me now but the number of users can potentially increase exponentially.
The other idea I had was to do a query like this:
select `username` from `ballots` where `ballot` like '12,%'
and if that returns results I'm done because position 1 is the leading spot. But if that returned 0 results I'd do:
select `username` from `ballots` where `ballot` like '*,12,%'
where * is a wildcard character that will match one number and one number only (unlike the %). But I don't know if this can actually be done.
Anyway does anyone have any suggestions on how best to do this?
Thanks
I'm not sure I understood correctly what you want to do - to get a list of users who have a given number in the 'ballot' field ordered by its position in that field?
If so, you should be able to use MySQL FIND_IN_SET() function:
SELECT username, FIND_IN_SET(12, ballot) as position
FROM ballots
WHERE FIND_IN_SET(12, ballot) > 0
ORDER BY position
This will return all rows that have your number (e.g. 12) somewhere in ballot sorted by position you can apply LIMIT to reduce the number of rows returned.

Categories