Is it possible to make query result in running another query? [duplicate] - php

This question already has an answer here:
Using results from one MySQL query in another query in a PHP Envirnment
(1 answer)
Closed 10 years ago.
I have this query:
$aircraft_query = "SELECT COUNT(aircraft) as total, aircraft FROM db_pireps WHERE pilotid = $pilotid GROUP BY aircraft ORDER BY total DESC LIMIT 6";
$planes = DB::get_results($aircraft_query);
And using a foreach statement, I can generate rows in a table to show aircrafts flown by a pilotid. However, I'd like now the RESULT to link to another table and extract data from there, such as aircraft type, in a fullname column.
I have this: <?php echo $aircraft->fullname; ?> but that data is in a different table. So, if aircraft was 30, it would access 30th record in db_aircrafts table and take the fullname column. How can I do this? Is it even possible?

What you need is called a table JOIN (also see JOIN in MySQL manual):
SELECT
COUNT(a.aircraft) as total
, a.aircraft
, b.fullname AS aircraft_name
FROM db_pireps AS a
JOIN db_aircraft AS b
ON a.aircraft = b.id
WHERE pilotid = {$pilotid}
GROUP BY aircraft
ORDER BY total DESC
LIMIT 6

You should use SQL Joins.
SELECT COUNT(A.aircraft) as total, A.aircraft, B.fullname
FROM db_pireps A
LEFT JOIN pilot_data_table B ON A.pilotid = B.id
WHERE A.pilotid = $pilotid
GROUP BY A.aircraft ORDER BY total DESC LIMIT 6

Related

SQL query to get all posts from a table in the db but max 5 entrys from a specific user? [duplicate]

This question already has answers here:
Using LIMIT within GROUP BY to get N results per group?
(14 answers)
Closed 2 years ago.
I´m building a php-blog system and want to display all posts but max five from each user on the start page.
I thinking of do this with a query in the database, but I´m lost on how to do that.
The count() function I guess will come in handy, but can somebody help me
This is my function today, and I just whant to improve it to get max five posts from each user
protected function getAllPostsDB() {
$sql = "SELECT recipes.Recipe_ID, recipes.Title, recipes.Short_description, recipes.Step_by_step,
recipes.create_date, recipes.last_mod_date, recipes.Portions, recipes.imgPath, users.Username
FROM recipes
JOIN users
ON recipes.User_ID = users.User_ID
ORDER BY recipes.create_date DESC";
$stmt = $this->connect()->query($sql);
/* fetch all is already set to associative array*/
$result = $stmt->fetchAll();
return $result;`
If you are running MySQL 8.0, just use window functions:
SELECT r.Recipe_ID, r.Title, r.Short_description, r.Step_by_step,
r.create_date, r.last_mod_date, r.Portions, r.imgPath, u.Username
FROM (
SELECT r.*, ROW_NUMBER() OVER(PARTITION BY User_ID ORDER BY create_date DESC) rn
FROM recipes r
) r
INNER JOIN users ON r.User_ID = u.User_ID
WHERE r.rn <= 5
ORDER BY r.create_date DESC
This gives the last five recipes per user, as designated by column create_date. You can change the ORDER BY clause of ROW_NUMBER() to some other column or set of columns if you want another sort rule.

How select next row pagination in sql

I'm sorry I'm weak for English.
i echo 2 row in each page . how echo next 2 row
SELECT *
FROM `mzmx_post`
JOIN mzmx_post_category
WHERE mzmx_post.id = mzmx_post_category.post_id AND zmx_post_category.category_id = 5
ORDER BY id DESC
LIMIT 2
You can use the two-arguments form of LIMIT to offset the result by a given number of rows, like:
SELECT *
FROM `mzmx_post`
JOIN mzmx_post_category ON mzmx_post.id = mzmx_post_category.post_id
WHERE mzmx_post_category.category_id = 5
ORDER BY id DESC
LIMIT 2, 2 -- fetch records 3 and 4
This gives you the second page. If you want the third page, then:
LIMIT 4, 2
And so on.
Note that I modified your query so the joining condition between the tables is placed in the ON clause of the join rather than in the WHERE clause.
Better add one extra column (e.g. mzmx_post_key bigint) of Long type in each table and have sequential value on that column. Use that column to fetch data from DB from page wise.
sqL suery should look like:
SELECT *
FROM `mzmx_post`
JOIN mzmx_post_category ON mzmx_post.id = mzmx_post_category.post_id
WHERE mzmx_post_category.category_id = 5 and mzmx_post_key> ##last record key##
ORDER BY mzmx_post_key ASC
LIMIT 2
The basic idea is to use
LIMIT n,o
where n is the results per page
o is the offset from the first result
for the p-th page the offset would be
o = p * n
where p = 0,1,2,....

Displaying records using inner join sql query from more than 2 combinations parameters in php

I am new to PHP and SQL; I am writing a SQL query to display records with the following logic:
There are 9 cells in sql table. I want to search records using combinations of 3 parameters. That are search between 2 dates, search in location and search in property category type.
Search criteria looks like this:
Date From : _________(date picker) - Date Till:______________(date picker)
Sales Agent : Dropdown ( dehi, mumbai,.....,)
Mobile : __________ (text)
Results Combination Required:
a. All 3 combination True - (User Fills the date, sales agent, mobile.)
b. Either of the combination is True. (User only fills either of one parameter.)
c. Only 2 Combination are True. (User fills 2 parameter combination ie, date and mobile(or) mobile & sales agent (or) sales agent & date)
Problem: I'm not able to do only one combination.
Here is my SQL query and page syntax:
if(isset($_POST["submit"]))
{
$date11=$_POST["date1"];
$date22=$_POST["date2"];
$salesagent1=$_POST["salesagent"];
$mobile1=$_POST["mobile"];
$result = "select
ordertable.order_date,
ordertable.order_id,
customer.cust_name,
customer.cust_mobile,
customer.cust_email,
customer.cust_city,
ordertable.quantity,
ordertable.total,
orderstatus.order_sta,
salesagent.name
from customer inner join ordertable
on customer.custid=ordertable.cust_id inner join salesagent
on salesagent.said=ordertable.sales_id inner join orderstatus
on orderstatus.id= (select order_statusid from orderhistory where order_id1= ordertable.order_id order by date_added desc limit 1)
where (ordertable.order_date between '$date11' and '$date22') or (customer.cust_mobile='$mobile1') or (ordertable.sales_id='$salesagent1')
order by ordertable.order_id desc";
$records=mysqli_query($CON,$result);
Set null or whatever you choose to do, to each parameters when it is empty:
$result = "select
ordertable.order_date,
ordertable.order_id,
customer.cust_name,
customer.cust_mobile,
customer.cust_email,
customer.cust_city,
ordertable.quantity,
ordertable.total,
orderstatus.order_sta,
salesagent.name
from customer inner join ordertable
on customer.custid=ordertable.cust_id inner join salesagent
on salesagent.said=ordertable.sales_id inner join orderstatus
on orderstatus.id= (select order_statusid from orderhistory where order_id1= ordertable.order_id order by date_added desc limit 1)
where ('$date11' IS NULL OR '$date22' IS NULL OR ordertable.order_date between '$date11' and '$date22') AND ('$mobile1' IS NULL OR customer.cust_mobile='$mobile1') AND ('$salesagent1' IS NULL OR ordertable.sales_id='$salesagent1')
order by ordertable.order_id desc";

Query first, then randomize, and then retrieve remaining fields [duplicate]

This question already has answers here:
MySQL: Alternatives to ORDER BY RAND()
(9 answers)
How to request a random row in SQL?
(30 answers)
Closed 6 years ago.
I have a table with about 70 columns and 120,000 rows of data. What I want to do is randomize a record and then displaying the values of others columns of this record.
If I do fetch all data,
$result=mysqli_query($link, 'SELECT id, column1, column2, column3, ..., column 70 from table');
while ($row=mysqli_fetch_array($result))
{
$info[] = array('id'=>$row['id'], 'column1'=>$row['column1'], ...);
}
$randindex = rand(0,count($info));
$id = $info[$randindex]['id'];
echo $info[$randindex]['column1']; echo $info[$randindex]['column2']; ....
I'm afraid that this will significantly slow down the process. So I want to query only the ID before randomization, and then use the randomized ID to retrieve the other values of that record in the database.
$result=mysqli_query($link, 'SELECT id from table');
while ($row=mysqli_fetch_array($result))
{
$info[] = $row['id'];
}
$randindex = rand(0,count($info));
$id = $info[$randindex];
and then retrieve all other fields of this particular record somehow. I asked how to do this in SQL here but I would like to know if there is any more efficient way by other means besides SQL. Do I need to do a loop like this?
In your code, do the following:
select min(id) as minid, max(id) as maxid
from table;
Then use php to generate a random id and do:
select t.*
from table t
where t.id >= $randid
order by id
limit 1;
With an index on id -- and reasonable assumptions about there not being too large gaps in the values -- then this will work well.
You can do the same thing in just one query:
select t.*
from table t cross join
(select min(id) as minid, max(id) as maxid from table) tt
where t.id >= minid + rand() * (tt.maxid - tt.minid)
order by id
limit 1;
you can use ORDER BY RAND() directly in the sql query:
SELECT * FROM table ORDER BY RAND() LIMIT 1
ORDER BY RAND() actually makes random order of you rows, and then you just do LIMIT 1 in order to get only one row, the first one.
I do not think it is valid. I think it's faster execute just one query with ORDER BY RAND ()

select 3 rows from mysql table, then get each row's specific column

Select 3 rows from table1
Get a specific column data out of each row.
Then use that each column data obtained , to make a query again to get data from table2.
Store the data obtained in step 4 into a variable for each row.
Then put them in json array (table 1 , 3 rows + table 2's data(each of them).
I am building a rank table, it displays top 3 users with their rank name.
For example:
User1 has 2000 points , user 2 has 4000points , user 3 has 10k points , so the top 3 user is :
user 3 > user 2 > user 1
So , i want the php to go to 'users' table and get the top 3 members using this:
$query = mysql_query("SELECT * FROM users ORDER BY pts DESC LIMIT 3");
$rows = array();
while($r = mysql_fetch_assoc($query)) {
$rows[] = $r;
}
Table structure for 'user':
1.username(varchar)
2.pts(int)
After the rows are put into an array , how can i get 'points' for each of the row in that array.
Then go to 'rank' table to get their ranknames.
Table structure for 'rank':
1.rank(varchar)
2.pts(int)
Inside rank table there is 'pts' to let php choose compare which rank the user is at based on the points from each row of the array.
Normally i would use this if its only for 1 user , but for multiple users , im not sure:
$result = mysql_query("SELECT * FROM rank WHERE pts <= '$upts' ORDER BY pts DESC LIMIT 1")
or die(mysql_error());
Then after getting the rank for the top 3 users , php will now add the ranks to each of the user(row) in that array(of course , add it to the rank owner, not just simply place it in).
Then JSON encode it out.
How can i do this?
I am not sure if this is what you want. That is combine the two query into one query. Please take a look at http://sqlfiddle.com/#!2/ad419/8
SELECT user.username,user.pts,rank.rank
FROM user LEFT JOIN rank
ON user.pts <=rank.pts group by user.id
UPDATED:
For extracting top 3, could do as below;
SELECT user.username,user.pts,rank.rank
FROM user LEFT JOIN rank
ON user.pts <=rank.pts
GROUP BY user.id
ORDER BY pts DESC LIMIT 3
If i understand correctly, you need to get values from Rank and Users tables. In order to do that in just one query You need to add FK (Foreign Key) to the Rank table that points to a specific user in the Users table.
So you need to add userId to the Rank table and then you can run:
SELECT r.rank, u.points from users u,rank r where u.userId = r.userId
This is roughly what you need.
Not quite the answer to your exact question, but this might be of use to you: How to get rank using mysql query. And may even mean that you don't require a rank table. If this doesn't help, I'll check back later.
Use this query
$query = "SELECT
u.pts,
r.rank
FROM users as u
left join ranks as r
on r.pts = u .pts
ORDER BY pts DESC
LIMIT 3";
This will bring what you required without putting into an array
$rec = mysql_query($query);
$results = arrau();
while($row = mysql_fetch_row($rec)){
$results[] = $row;
}
echo json_encode($results);
It looks like what you're trying to do is retrieve the rank with the highest point requirement that the user actual meets, which isn't quite what everyone else is giving here. Fortunately it is easily possible to do this in a single query with a nice little trick:
SELECT
user.username,
SUBSTRING_INDEX(GROUP_CONCAT(rank.rank ORDER BY pts DESC),",",1) AS `rank`
FROM user
LEFT JOIN rank ON user.pts >= rank.pts
GROUP BY user.id
ORDER BY pts DESC
LIMIT 3
Basically what the second bit is doing is generating a list of all the ranks the user has achieved, ordering them by descending order of points and then selecting the first one.
If any of your rank names have commas in then there's another little tweak we need to add on, but I wouldn't have thought they would so I've left it out to keep things simple.

Categories