Getting second row from Rails scope - mysql

second = Trade.with_currency(currency).h24.order('id desc').limit(1).offset(1).try(:price)
first = Trade.with_currency(currency).h24.order('id desc').first.try(:price)
I want to get the price of the first and the second row. The first one is working but I have problems to get the second row. With above query I get nil back.
when i do the query for the second row directly in mysql it is working:
SELECT `trades`.* FROM `trades` WHERE `trades`.`currency` = 5 AND (created_at > '2014-01-11 16:20:06') ORDER BY id desc LIMIT 1 OFFSET 1;

prev = Trade.with_currency(currency).order('id desc').limit(1).offset(1).first.try(:price)
this is the solution - I added to select the first result offsetting by 1.

If you just need the values:
Trade.with_currency(currency).h24.order('id desc').pluck(:price).first(2)
The pluck method fetches just the values and first(2) is used to pull the first two values.

with offset(1) add first in the statement
it will go like
second = Trade.with_currency(currency).h24.order('id desc').limit(1).offset(1).first.try(:price)

Related

Select data from table using SQL query

I have a table name "chat_details" I wanna access only data with green underline according to time, I use the following query
//suppose $user_id = 1;
"SELECT *
FROM chat_details WHERE from_user_id='$user_id' OR to_user_id='$user_id' ORDER BY time DESC"
It fetch all the rows because all rows contain user_id = 1 in one of the column, but i need only green underline rows as compare to red one because green one are latest according to time(column), how can i fetch only these green underlines?
This is one posible query, that should solve your question.
SELECT *
FROM chat_details c
WHERE (c.from_user_id='$user_id' OR c.to_user_id='$user_id')
AND NOT EXISTS (
SELECT 1 FROM chat_details d
WHERE d.from_user_id = c.from_user_id
AND d.to_user_id = c.to_user_id
AND d.time > c.time)
ORDER BY c.time DESC"
Actually I could not test, hope I haven't made a mistake.
The query selects all data as in your query, but only thoose which haven't a newer chat between the two users.
For the EXISTS keyword see http://www.mysqltutorial.org/mysql-exists/

Select a random row with where statement is taking to long

I want to select a random row with a specific where statement but the query is taking to long (around 2.7 seconds)
SELECT * FROM PIN WHERE available = '1' ORDER BY RAND() LIMIT 1
The database contains around 900k rows
Thanks
SELECT * FROM PIN WHERE available = '1' ORDER BY RAND() LIMIT 1
means, that you are going to generate a random number for EVERY row, then sort the whole result-set and finally retrieve one row.
That's a lot of work for querying a single row.
Assuming you have id's without gaps - or only little of them - you better use the programming language you are using to generate ONE random number - and fetch that id:
Pseudo-Example:
result = null;
min_id = queryMinId();
max_id = queryMaxId();
while (result == null){
random_number = random_beetween(min_id, max_id);
result = queryById(randomNumber);
}
If you have a lot of gaps, you could retrieve the whole id-set, and then pick ONE random number from that result prior:
id_set = queryAllIds();
random_number = random_beetween(0, size(id_set)-1);
result = queryById(id_set[random_number])
The first example will work without additional constraints. In your case, you should use option 2. This ensures, that all IDs with available=1 are pre-selected into an 0 to count() -1 array, hence ignoring all invalid ids.
Then you can generate a random number between 0 and count() -1 to get an index within that result-set, which you can translate to an actual ID, which you are going to fetch finally.
id_set = queryAllIdsWithAvailableEqualsOne(); //"Condition"
random_number = random_beetween(0, size(id_set)-1);
result = queryById(id_set[random_number])

How to Get sum() of single column values

I have bellow snippet table structure.In this table there is one row count_set that have two values first is 1 and second is 1 here i have to make the sum of this value the sum answer will be 2.
I tried with bellow query but not getting sum value its getting sum with blank value.
so can any one tell me how to do this.
$sql_chk_current_sum_count = "SELECT sum(count_set) FROM wp_lead_count WHERE
end_date = $end_date";
$final_sum= $wpdb->get_results($sql_chk_current_sum_count) or die(mysql_error());
Try this:
SELECT sum(count_set) FROM wp_lead_count WHERE
date_format(end_date,'%Y-%m-%d') = date_format($end_date,'%Y-%m-%d');

How to get the row number from a while loop of mysql_fetch_array for each loop?

I have a simple while loop like this
while($row = mysql_fetch_array($result)){
}
It fetches many rows one by one and it is fine.
But i have add some extra features according to the row number.
when row number=1( first row)-do something
when row number=2( second row)-do something new
how can i get that ROW NUMBER of the each row?
Add a count variable:
$count = 1;
while ( $row = mysql_fetch_array( $result ) ) {
// do your work here
$count++;
}
You will have to include the row number in your select SQL. So updated your MySQL SQL Statement that fetches the rows, to include the row number as follows.
select #rownum:=#rownum+1 ‘row_number’, * from your_table, (SELECT #rownum:=0) r
This will create a variable rownum, initialize with value 0 & increase it by 1 for every record. Each row will have a column called row_number with ascending number starting from 1.
Then in your while... loop check for this row_number value and do processing accordingly.
Reference: See this post for another approach that involves creating a separate variable in SQL statement.
add an extra field in the select called row like this
SELECT #row:=IFNULL(#row,0)+1 as row,
your_columns
FROM your_tables

MySQL update with two subqueries

I'm trying to update one column of MySQL table with subquery that returns a date, and another subquery for the WHERE clause.
Here is it:
UPDATE wtk_recur_subs_temp
SET wtk_recur_date = (SELECT final_bb.date
FROM final_bb, wtk_recur_subs
WHERE final_bb.msisdn = wtk_recur_subs.wtk_recur_msisdn)
WHERE wtk_recur_subs_temp.wtk_recur_msisdn IN (select final_bb.msisdn
from final_bb)
The response from the MySQL engine is "Subquery returns more than 1 row".
Use:
UPDATE wtk_recur_subs_temp,
final_bb,
wtk_recur_subs
SET wtk_recur_subs_temp.wtk_recur_date = final_bb.date
WHERE final_bb.msisdn = wtk_recur_subs.wtk_recur_msisdn
AND wtk_recur_subs_temp.wtk_recur_msisdn = final_bb.msisdn
The error is because:
SET wtk_recur_date = (SELECT final_bb.date
FROM final_bb, wtk_recur_subs
WHERE final_bb.msisdn = wtk_recur_subs.wtk_recur_msisdn)
...the final_bb.date value is all the date values where the final_bb and wtk_recur_subs msisdn column values match.
This may come as an utter shock to you, but one of your subqueries is returning more than one row!
This isn't permitted in the circumstance you've set up. Each of those two subqueries must return one and only one row. Or no rows.
Perform each subquery on it's own and determine which one is returning more than one row. If they shouldn't return more than one row, your data may be wrong. If they should return more than one row, you'll either want to modify the data so they don't (as I assume you expect), or add a LIMIT clause. Or add an aggregate function (like MAX) outside the query to do something proper with the multiple rows being returned.