MYSQL pickup Random row after order by - php

I want to pick a random row after doing an order by.
My result can sometime return 2 rows with same value. So what i want to do it that i want to select 1 row randomtly between the same rows returned.
In the below example i want to return 1 row between the 2 same rows returned.
Thanks.
select nondox, account, id
from rates2 where weight='32' and country_code='US'
and service like '%INT%'
order by nondox,account
Result of the above query is
nondox account id
276.16 610661731 25805209
276.16 610798714 2108989
391.68 610662766 1281799

Can provide more details ?
This will eliminate the similar nondox values it's not completely random but it should work.
select account, id , nondox from rates2 where weight='32' and country_code='US' and service like '%INT%' group by nondox order by nondox,account

you can use function RAND() that generates a random value for each row in the table
SELECT * FROM table_name
ORDER BY RAND()
LIMIT 1;
for more informations checkout this link

you can put the result in an array, then create a random integer with random(with limit) the output the values of the index from random.
example random outputs 2, you return array[random+1] ie array[3]

Related

php pg_fetch_array only show first result

i query to check if a point(input) is intersect with polygons in php:
$sql1="SELECT ST_intersects((ST_SetSRID( ST_Point($startlng, $startlat),4326))
, zona_bahaya.geom) as intersek
FROM zona_bahaya";
$query1 = pg_query($conn,$sql1);
$check_location = pg_fetch_array($query1);
if (in_array('t',$check_location)) {
dosemthing1;}
else {dosomething2;}
it's work peroperly before i update the data
after data updated, it's only show the first row when i check the pg_fetch_array result. here is the result {"0":"f","intersek":"f"} .
i try to check from pgadmin and it's can show 8 result (1 true(intersected) and 7 false(not intersect)) using updated data with this query:
SELECT ST_intersects((ST_SetSRID( ST_Point(110.18898065505843, -7.9634510320131175),4326))
, zona_bahaya.geom) as intersek
FROM zona_bahaya;
to solve it, i order the query result descended so the 'true' gonna be the first like this:
order by intersek desc
anybody can help me to findout way it just only show the first row???
here some geom from STAsText(zonabahaya.geom) not all of them : MULTIPOLYGON(((110.790892426072 -8.19307615541514,110.791999687385 -8.19318330973567,110.794393723931 -8.1927980624753,110.794586347561 -8.19205508561603,110.795329324421 -8.19120203811094,110.796540101525 -8.19023891996003,110.797503219676 -8.18933083713203,110.798576408472 -8.18919324882476,110.79929186767 -8.18957849608512,110.800337538805 -8.19059664955894,110.800585197758 -8.19150473238694,110.80022746816 -8.19238529755349,110.799787185576 -8.19290813312112,110.799589319279 -8.19300706626968,110.798788231202 -8.19299429992581,110.798537293576 -8.19311976873883,110.79850269889 -8.1933090511224,110.798620939451 -8.19433728092441)))
In order to filter only the records that intersect you have to use ST_Intersects in the WHERE clause:
SELECT *
FROM zona_bahaya
WHERE ST_Intersects(ST_SetSRID(ST_Point(110.18, -7.96),4326),zona_bahaya.geom);
Since you're dealing with points and polygons, perhaps you should take a look also at ST_Contains.
In case you want to fetch only the first row you must set a limit in your query - either using LIMIT 1 or FETCH FIRST ROW ONLY -, but it would only make sense combined with a ORDER BY, e.g.
SELECT *
FROM zona_bahaya
JOIN points ON ST_Intersects(points.geom,zona_bahaya.geom)
ORDER BY gid
FETCH FIRST ROW ONLY;
Demo: db<>fiddle

Use PHP mt_rand() instead of MySQL rand() to avoid slow query

I have a PHP file that looks for a random id from a MySQL DB, but when the table is big enough it gets slow.
ID row has gaps.
Original
$sql = "SELECT * FROM definiciones ORDER BY rand() LIMIT 1";
Idea
$random = mt_rand(0, 10000);
$sql = "SELECT * FROM definiciones WHERE id = (SELECT max(id) FROM definitiones WHERE id < $random)";
I know the exact amount of rows in the DB beforehand. Is it a good idea to replace the original query?
Is it a good idea to replace the original query?
Yes, but there's a simpler way of expressing this:
SELECT * FROM definiciones WHERE id >= ? ORDER BY id LIMIT 1
With ? set to a random number between 0 and the maximum ID in the table.
Now, an improvement: If there are any gaps in the values of id, the results from the previous method will be skewed somewhat. (For instance, if there are no rows with id < 100, then a row with id = 100 will be selected much more often than one with id = 101.) You can avoid this by using a separate column for randomization. First, you will need to add the column:
ALTER TABLE definiciones ADD COLUMN randomval FLOAT NOT NULL,
ADD KEY randomval (randomval);
UPDATE TABLE definiciones SET randomval = RAND();
Then, to select a fairly chosen random item:
SELECT * FROM definiciones WHERE randomval > ? LIMIT 1;
using a random value between 0 and 1 for the parameter.
There is a small chance that this will return no rows (if RAND() selects a value greater than the highest value in the table). If this happens, repeat the query.
You will need to set randomval = RAND() when inserting new rows into the table.

How to select one row from multiple which are with same column name in mysql?

I have a table with with columns name:
id
message
sender
chat_id
I want to get one row from number of rows with same chat_id ,during while loop fetch.
What Will be the MySQL Query
If you only want one row, one of those columns needs to have unique data so you can add it to the WHERE clause
SELECT id,message,sender,chat_id from information WHERE id=2 for example.
SELECT id,message,sender,chat_id from information WHERE chat_id=5 AND sender='mark'
OR during the while loop, match the column and grab whatever you want from it.
But again, it needs to be a unique combination of data otherwise it'll be overwritten by the previous.
while($row = $result->fetch_assoc()){
if($row['sender'] == 'mark' && $row['chat_id'] == '5'){
$thisIsMyRow = $row['id'];
}
Please could you explain more? What is it you're trying to achieve?
Say this is your query:
SELECT id,message,sender,chat_id from messages WHERE chat_id=1
You may have 200 rows that match that query. To return just one result, you can do a couple of things.
If you want the latest message, you can do this:
SELECT id,message,sender,chat_id from messages WHERE chat_id=1 ORDER BY id DESC LIMIT 1
another example, latest 5 messages
SELECT id,message,sender,chat_id from messages WHERE chat_id=1 ORDER BY id DESC LIMIT 0,5
In addition when you take it back into PHP, rather than going through the loop, you can JUST do this:
$row = $result->fetch_assoc()
As our query is only returning 1 row, you don't need to loop through. You can do this when your query returns multiple results - but it'd be better to optimise your query.
I can advise better if you are able to elaborate.
while($row = $result->fetch_assoc()){
$query = "SELECT id, message, sender,chat_id FROM messages WHERE Y = X AND Z = $K LIMIT 1";
}
replace the WHERE part with whatever column you want

Random data mysql

I have table in mysqli database now i want to get 1 result random
This is code mysql
$cid = $_GET['id'];
$ans = $db->query("select * from result where cat_id='$cid' limit 1");
$rowans = $ans->fetch_object();
echo"
<h4>".$rowans->title."</h4><br>
<img src='".$rowans->img."' style='width:400px;height:300;' />
<p>".$rowans->desc."</p>";
in this code i get 1 result but not random always gives me the same result
SQL:
SELECT *
FROM result
ORDER BY rand()
LIMIT 1
LIMIT orders the rows by the primary key of the table, so you always get the same one (the "first" row according to that key).
Try:
SELECT * FROM result WHERE cat_id='$cid' ORDER BY RAND() LIMIT 0,1;
You can think of it this way: it first orders the results by a random order, then picks the first one.

ID from array NOT in table

It seems that I have to edit my question again - these down votes are getting frustrating...
I have an array of ids and a table to check it with. This is the query I use:
SELECT COUNT(*) FROM orders WHERE order_id IN (...
When this number isn't equal to the number of ids in the array, I need to get those values from the array that I have, that do not exist in the table. Is there a more optimal way to do this than making some temporary table, and selecting from it?
EDIT: For all those suggesting inserting NOT in the first query - I do not need all the rows from my table that do not match the values in the array - I need the values from the ARRAY itself...
For example, I have an array of three ids - "1","2","3". In the table I have ids "2" and "3". I check the array with my query:
SELECT COUNT(*) FROM orders WHERE order_id IN (1,2,3)
I get the number 2 as a result of this query, and that doesn't match the number of ids I have in the array, which is 3. I need a query that will get the missing id from the array I submitted, in this case the id I need is "1"
I don't think there's a clean SQL-only solution, because there's no way to SELECT from an array. However, instead of using a temporary table, you could return all the IDs that are found in the table, and do the NOT on the PHP side.
So select the result of this into an array, $existing_orders:
SELECT order_id FROM orders WHERE order_id IN (...);
Then you have:
$all_orders = array(1, 2, 3); // IDs you're looking for
$existing_orders = array(2, 3); // IDs that were found in the table
$not_existing_orders = array_diff($all_orders, $existing_orders);
print_r($not_existing_orders); // Array( [0] => 1 )
OK THAT´S clear now:
Then you will have to make something like this:
select id from order where id IN ( your list )
create a second array with the found values
and then use php array function array_diff
select * from orders where order_id NOT in (...

Categories