Need to find the database value from greatest id available in output - php

By running the following SQL command:
SELECT inl_cbsubs_subscriptions.user_id, inl_cbsubs_payment_items.subscription_id,
inl_cbsubs_payment_items.stop_date
FROM inl_cbsubs_subscriptions INNER JOIN
inl_cbsubs_payment_items ON inl_cbsubs_subscriptions.id=inl_cbsubs_payment_items.subscription_id
WHERE inl_cbsubs_subscriptions.user_id=596;
I get the following output:
As you can see, there are a variety of id values that are not always incremental. I need a way to modify the SQL statement so that the search will filter through the results and only provide a single output from the item which has the greatest id value. So, to show what I would like to see from the above example, here is a screenshot:
I am running the SQL statement in a PHP script, so if I need to implement any dynamic variables that would be available. Thanks you for your time.

You can use a DESC sorting on id and limit result with LIMIT 1.

Related

how get random questions from database include Categories?

Hallo i try to make a simple quiz application in php based on math tests from many years. I have database with such columns:
-id
-pytanie
-a
-b
-c
-d
-poprawna
-rok_id
-typ_id
I use rand function to get random id and next i use this in sql answer to get random question.
However id dont know how get radnom question for example random one question include yera_id=1
Firstly i use $numer=rand(1,1800)
My sql select is such as\
select pytanie, a,b,c,d, nazwa, rok_liczba, nazwa_typu, poprawna from pytania left join rok on rok.id= pytania.rok_id left join typ on typ.id=pytania.typ_id where typ_id=1 and pytania.id=".$numer.""
When i add to sql select ,,where year_id=1" i must click many time to hit when rand get 1 beacuse otherwise i dont get any resoult. It possible to rand from records ho are resoult a sql answer ?
You are computing a random number outside of the database then using it as a filter: but there is no guarantee that you have a record that matches your random value and the other filter on the question type.
I would recommend doing the random sort in the query itself. This should be as simple as adding this at the end of your query:
select ...
from ...
where typ_id = 1
order by rand() limit 1
Note that the exact syntax may vary across databases - the above is MySQL syntax.

How to get a SUM of an attribute in Sphinx?

I have Sphinx Search running on production, performing search with keywords, accessed through official sphinxapi.php. Now I need to output a sum of an attribute called price along with search results, similar to SQL query "SELECT SUM(t.price) from table_name t WHERE condition". This data is supposed to be displayed on a web page like "Showing 1 - 10 out of 12345 results, total cost is $67890". As documentation says, SUM() function is available when used with GROUP BY. However, the documentation does not provide enough details on implementation, googling and searching Stackoverflow doesn't help much as well.
Questions:
How should I group the search result?
Can it be performed with 1 Sphinx request, or do I have to get the search results first and then query Sphinx again to get the sum of found documents?
Please advise. An example will be really helpful. Thank you.
You will need to run a second query. The 'sum' is wanted on the WHOLE result set, whereas normal grouping, the aggregation is run per row. In your example, there is an implicit GROUP BY '1' which aggregates all rows.
So would need to use Grouping to do same in sphinx.
http://sphinxsearch.com/docs/current.html#clustering
Using the aggregation function is relatively easy, use with setSelect, but not sure SetGroupBy has a syntax to group all rows so will have to emulate it.
//all normal setup need for normal query here
$cl->SetLimits($offset,$limit);
$cl->AddQuery($query, $index);
//add the group query
$cl->setSelect("1 as one, SUM(price) as sum_price");
$cl->setGroupBy("one",SPH_GROUPBY_ATTR); //dont care about sorting
$cl->setRankingMode(SPH_RANK_NONE); //no point actually ranking results.
$cl->SetLimits(0,1);
$cl->AddQuery($query, $index);
//run both queries at once...
$results = $cl->RunQueries();
var_dump($results);
//$results[0] contains the normal text query results, use its total_found
//$results[1] second contains just the SUM() data
This also shows setting up as Multi-Queries!
http://sphinxsearch.com/docs/current.html#multi-queries

limit to one result causes my php sql query to return false [duplicate]

A quick Question. Suppose I have the following two queries:
SELECT TOP 2 * FROM Persons;
and
SELECT * FROM Persons limit 2;
I want to know the difference between the execution of the above 2 queries?
Basically, I want to know when should I use the limit keyword and when it is appropriate to use the top keyword.
Also, How does the database return results based on the above 2 queries.
If you are using SQL Server use TOP.
if you are using MySQL or PostgreSQL use LIMIT!
AFAIK there is no product that currently supports both. Here's one list of current implementations and here's another (covers more products but in less detail)
As stated in my comment for Martin Smith's answer above, there are products that support both, LIMIT and TOP (as you can see here). The difference is that TOP only selects the first n records, but LIMIT allows the definition of an offset to retrieve a specific range of records:
SELECT * FROM ... LIMIT 5 OFFSET 10
This statement selects the 5 records, after skipping 10 records and this isn't possible with TOP.
The example I posted is only checked against the DBS I linked above. I didn't check a SQL standard, because of a lack of time.
TOP & LIMIT both work on amazon Redshift
limit works on MySQL and PostgreSQL, top works on SQL Server, rownum works on Oracle.
There is no difference. The TOP and LIMIT keywords function identically, and will return the same thing.
The DISTINCT command and the TOP command can't work together.
The DISTINCT command and the LIMIT command do work together.
So if you are using DISTINCT you must use LIMIT.
The difference between top and limit is, top only work with single table where as limit can work with join as well
one big mistake, LIMIT is slowly because select is return full and then database server return only limited data. When it is posible used to TOP.

Solution Mysql Random query migrate when goto another page

I have table Post, user can search Post by find by keyword.
So, i using SQL query by like keyword and order by RAND().
When show result, i using GridView and Pagination data. And has problem, when go to another page. Example from page 1 go to page 2 with same keyword. i Will Query again and order by Rand(). So some data in page 1 can appear in page 2.
That data duplicate and not good.
So how can i solve this problem. and data query when goto page other will same with data in the first query.
I using Yii2 in my project.
Ok, I think I get it. Example MySQL query:
SELECT * FROM articles WHERE name LIKE '%tag%' LIMIT 0, 20;
Or you can use MySQL's MATCH() instead of LIKE, it doesn't matter. Then LIMIT 0, 20 is limit, how many results to show for the first page. For the second page it should be LIMIT 1, 20. This one you know I except. Then you get an array of results in the PHP, and want to get random values. PHP has such a function for you and it is called suffle().
So you just use shuffle($results); and then you can print them with foreach or whatever you use to print the data. Note that shuffle() returns boolean, so do not use $results = shuffle($results);. Hope this helps.

Iterating through a sub-section of result resource in PHP-MySQL

In my program I launch an SQL query and get back a result resource. I then iterate through the rows of this result resource using the mysql_fetch_array() function and use the contents of the fields of each row to construct a further SQL query.
The result of launching this second query is the first set of results that I want. However, because the number of results produced by doing this is not many I want to make the search less specific by dropping the last record used to make the query.
e.g. the query which produces the first set of results I want could be:
SELECT uid FROM users WHERE (gender=male AND relationship_status=single
AND shoe_size=10)
I would then want to drop the last record so that my query became:
SELECT uid FROM users WHERE (gender=male AND relationship_status=single)
I have already written code to produce the first query but as I mentioned above I use the mysql_fetch_array function to iterate through ALL of the records. In subsequent "rounds" I only want to iterate through successively less records so that my query is less specific. How can I do this?
This seems like an very inefficient method too - so I'm welcome to any simple ideas which might make it more efficient.
EDIT: Thanks for the reply - Yeah I am actually doing this in my program. I am basically trying to implement a basic search algorithm by taking all the preferences a user has specified in the DB and using it to form a query to look for people with those preferences. So the first time search using all the criteria, then on successive attempts search using one less criteria and negate the user ids which were previously returned. At the moment I am constructing the query from scratch for each "round", but I want to find a way I can do this using the last query
Using the queries above, you could do:
SELECT uid
FROM users
WHERE uid NOT IN (
SELECT uid
FROM users
WHERE
(gender=male
AND relationship_status=single
AND shoe_size=10)
)
This will essentially turn your first query into a sub-query, and use that to negate the results returned. Ie, it will return all the rows, NOT IN the first query.

Categories