SQL statement improve for speed - php

i have this piece of code that selects all users from the table and another sql statement that counts the number of records for every user. the problem I'm facing is that i have a sql in a foreach loop which is not good for performance but i wasn't able to combine both of them in one statement. any advise?
$query = $db->getAll("SELECT * FROM users");
foreach($query as $v){
$tpl->setCurrentBlock('useri');
$query2 = $db->numRows("SELECT * FROM signups AS s INNER JOIN users AS u ON s.userid=u.id WHERE u.id={$v['id']}");
$tpl->setVariable('total',$query2);
$tpl->setVariable($v);
$tpl->parseCurrentBlock();
}

Try this query against your DB:
SELECT u.id, COUNT(s.*)
FROM users u
LEFT JOIN signups s ON s.userid = u.id
GROUP BY u.id
I hope I got it right. I have no SQL DB to test it right here. Important: You have to group by each field you select that is no aggregate.
Edit:
If it is not fast enough yet, an index on signups.userid may help. This is hypothetic, however, so you should check the Execution Plan your query engine generates.

$query = $db->getAll("
SELECT u.id, u.name, COUNT(*) total
FROM signups AS s RIGHT JOIN users AS u ON s.userid=u.id
GROUP BY u.id, u.name
ORDER BY u.name
");
foreach($query as $v){
$tpl->setCurrentBlock('useri');
$tpl->setVariable('total', $query['total']);
// ...
$tpl->parseCurrentBlock();
}

If I understand good your problem, initialize variable and in loop increase it.
int i;
foreach($query as $v){
$tpl->setCurrentBlock('useri');
$query2 = $db->numRows("SELECT * FROM signups AS s INNER JOIN users AS u ON s.userid=u.id WHERE u.id={$v['id']}");
$tpl->setVariable('total',$query2);
$tpl->setVariable($v);
$tpl->parseCurrentBlock();
i++;
}

Related

php mysql query combination

I first search all questions info. from "question" table including title, content, user etc.
the Code:
$sql = "select * FROM question where id>0 ORDER BY id ASC";
$result1 = mysql_query($sql);
$res=Array();
And then I want to search the user's point from "user" table. So I must search point for each user in each row from the result1
The Code:
while($rows=mysql_fetch_assoc($result1))
{
$res[]=$rows;
$user = $rows['user'];
$sql2 = "select point from user where name='$user'";
$result2 = mysql_query($sql2);
}
My problem is how to combine all the users' point(result2) with the questions info.(result1) together so that I can return a json for each row.
Use left join, as my understanding this work for you
$sql = "SELECT q.*, u.point AS point FROM question AS q LEFT JOIN user AS u ON q.user = u.name WHERE q.id > 0 ORDER BY q.id ASC";
$result = mysql_query($sql);
It's better go with the joins here i am giving you the query.i hope it may helps you
select * from question q,user u where q.id>0 ORDER BY id ASC
try something like this:using left join
select question.*,user.point FROM question left join user on user.name= question.name where id>0 ORDER BY id ASC

Using Where and Join together

So I have two tables, one storing the username and the other with their personal info. What I'm trying to get is a result where, I want to take the current active username and join it with the personal info table to get the ID, Username + their basic info to appear in a table. I came up with the query after googling, but it seems that I did something wrong. Can someone tell me what I did wrong?
users = the table that contain username
userinfo table with their basic info
$username is basically a variable that was stored in the $SESSION
<?php
$query = mysql_query("
SELECT users.UserID, users.Username, userinfo.FirstName, userinfo.LastName,
FROM users
WHERE users.Username = $username
INNER JOIN userinfo
ON users.UserID=userinfo.UserID");
?>
Assuming I have the parse data to table coding right below that specific code, what is wrong with the query?
Basically the error I keep getting is error #1064 at line #2 (when I run the query without the php code). Thanks in advance!
<?php
$query = mysql_query("
SELECT users.UserID, users.Username, userinfo.FirstName, userinfo.LastName
FROM users
INNER JOIN userinfo
ON users.UserID=userinfo.UserID
WHERE users.Username = $username
");
?>
Try this
<?php
$query = mysql_query("
SELECT users.UserID, users.Username, userinfo.FirstName, userinfo.LastName,
FROM users
INNER JOIN userinfo
ON users.UserID=userinfo.UserID
WHERE users.Username = $username");
?>
The syntax is -
SELECT col, ...
FROM <tbl_name> AS t1
INNER JOIN <join_tbl_name> AS t2
ON t1.col = t2.col
WHERE <cond>
See the below code. If you print it, you will find where error occurs.
echo $query = mysql_query("SELECT users.UserID, users.Username, userinfo.FirstName, userinfo.LastName FROM users WHERE users.Username = '$username' INNER JOIN userinfo ON users.UserID=userinfo.UserID");
or use
$sql="SELECT users.UserID, users.Username, userinfo.FirstName, userinfo.LastName FROM users WHERE users.Username = '$username' INNER JOIN userinfo ON users.UserID=userinfo.UserID";
if(!mysql_query($sql,$con))
{
echo "Unexpected Error <br/>";;
die (mysql_error());
}
where $con is mysql connection statement.
You have an extra comma at the end of field select. Try removing that part:
$query = "SELECT users.UserID, users.Username, userinfo.FirstName, userinfo.LastName
FROM users
INNER JOIN userinfo
ON users.UserID=userinfo.UserID
WHERE users.Username = $username";

MySQL joins: how to simplyfy the given query?

$sql="SELECT advertiser_name from broker_blocked_advertisers where pline=".$pLine." AND bid=".$cNr;
$result=mysqli_query($conn,$sql);
if(mysqli_num_rows($result)>0){
while($row=mysqli_fetch_array($result)){
$s=trim($row['advertiser_name']);
$sql2= "SELECT clientid from rv_clients where clientname='{$s}'";
$result2=mysqli_query($dbc,$sql2);
while($row2=mysqli_fetch_array($result2)){
$sql3= "SELECT campaignid from rv_campaigns where clientid=".$row2['clientid'];
$result3=mysqli_query($dbc,$sql3);
while($row3=mysqli_fetch_array($result3)){
$sql4= "SELECT bannerid from rv_banners where campaignid=".$row3['campaignid'];
$result4=mysqli_query($dbc,$sql4);
while($row4=mysqli_fetch_array($result4)){
$block_adr[]= $row4['bannerid'];
}
}
}
}
}
Anybody please suggest me to simplify the above code in a single query???.
The above code is really a wrong approach i think, please help how to short it out?.
Code description: Here i get one value from a sql table and by using that value i step forward to another query and so on.
Thanks in advance
Revised query and script:-
$sql = "SELECT d.bannerid
FROM broker_blocked_advertisers a
INNER JOIN rv_clients b ON a.advertiser_name = b.clientname
INNER JOIN rv_campaigns c ON b.clientid = c.clientid
INNER JOIN rv_banners d ON c.campaignid = d.ampaignid
WHERE a.pline=".$pLine." AND a.bid=".$cNr;
$result=mysqli_query($dbc,$sql);
while($row=mysqli_fetch_array($result))
{
$block_adr[]= $row['bannerid'];
}
This is the dreaded (n+1) latency death, four times over.
Every iteration through a loop is another network roundtrip. That's going to kill your performance.
Think "join". Bring all the data back in one round trip and sort it out on the client side.
Here's a simplified example:
select *
from campaign
join banner
on campaign.id = banner.campaign_id
That saves looping over campaigns.
All in one query
$sql="SELECT
bann.bannerid,camp.campaignid,c.clientid,b.advertiser_name as advname
from
broker_blocked_advertisers as b,
rv_clients as c,
rv_campaigns as camp,
rv_banners as bann
where b.pline=".$pLine."
AND bid=".$cNr."
AND c.clientname=advname.advertisername
AND camp.clientid=c.clientid
AND bann.campaign_id=camp.campaig_id"
YOU CAN USE A SINGLE QUERY LIKE THIS:
SELECT bannerid from rv_banners where campaignid=
(
SELECT campaignid from rv_campaigns where clientid=
(
SELECT clientid from rv_clients where clientname=
(
SELECT advertiser_name from broker_blocked_advertisers where pline=".$pLine."
AND bid=".$cNr;
)
)
);
SELECT "bannerId" FROM rv_banners A, rv_campaigns B, rv_clients C, broker_blocked_advertisers D
WHERE A.campaignid = B.campaignid AND B.clientid = C.clientname AND C.clientname = D.advertisername AND D.pline = ".$pline." AND D.bid = ".$cNr;

Mysql Join two Id's to get there Usernames

Im trying to get in Array that contains the results from a MYSQL query.
I have 2 ids stored in the table hitlist user_id and mark_id
they need to join in the table users to retrieve there usernames that match there id's and in the future other variables.
i have this working in a weird way and was hopeing to get this working in a more efficent simple way similar to this
$Hitlists = $db->query("SELECT * FROM hitlist JOIN users ON hitlist.user_id = users.id AND hitlist.mark_id = users.id")->fetchAll();
This is the code i have that is working...for now it looks like it might give me problems later on.
<?php
$index = 0;
$Hitlists = array();
$st = $db->query("SELECT * FROM hitlist JOIN users ON hitlist.user_id = users.id")->fetchAll();
$sth = $db->query("SELECT * FROM hitlist JOIN users ON hitlist.mark_id = users.id")->fetchAll();
foreach($st as $id)
{
$Hitlists[] = $id;
}
foreach($sth as $id)
{
$Hitlists[$index]['markedby'] = $id['username'];
$Hitlists[$index]['mark_id'] = $id['mark_id'];
$index++;
}
The way you are joining the table is wrong. You can get the exact records you want, you need to join users table twice to get the username of each ID
SELECT a.*,
b.username User_name,
c.username mark_name
FROM hitlist a
INNER JOIN users b
ON a.user_id = b.id
INNER JOIN users c
ON a.mark_id = c.id
and you can access
$result['User_name']
$result['mark_name']

Help construct a simple query Using 3 tables

Hey guys need some more help
I have 3 tables USERS, PROFILEINTERESTS and INTERESTS
profile interests has the two foreign keys which link users and interests, they are just done by ID.
I have this so far
$statement = "SELECT
InterestID
FROM
`ProfileInterests`
WHERE
userID = '$profile'";
Now I want it so that it selects from Interests where what it gets from that query is the result.
So say that gives out 3 numbers
1
3
4
I want it to search the Interests table where ID is = to those...I just don't know how to physically write it in PHP...
Please help.
Using a JOIN:
Best option if you need values from the PROFILEINTERESTS table.
SELECT DISTINCT i.*
FROM INTERESTS i
JOIN PROFILEINTERESTS pi ON pi.interests_id = i.interests_id
WHERE pi.userid = $profileid
Using EXISTS:
SELECT i.*
FROM INTERESTS i
WHERE EXISTS (SELECT NULL
FROM PROFILEINTERESTS pi
WHERE pi.interests_id = i.interests_id
AND pi.userid = $profileid)
Using IN:
SELECT i.*
FROM INTERESTS i
WHERE i.interests_id IN (SELECT pi.interests_id
FROM PROFILEINTERESTS pi
WHERE pi.userid = $profileid)
You are on the right track, lets say you execute the query above using this PHP code:
$statement = mysql_query("SELECT InterestID FROM `ProfileInterests`
WHERE userID = '$profile'");
Then you can use a PHP loop to dynamically generate an SQL statement that will pull the desired IDs from a second table. So, for example, continuing the code above:
$SQL = "";
while ($statementLoop = mysql_fetch_assoc($statement)) {
//Note the extra space on the end of the query
$SQL .= "`id` = '{$statementLoop['InterestID']}' OR ";
}
//Trim the " OR " off the end of the query
$SQL = rtrim($SQL, " OR ");
//Now run the dynamic SQL, using the query generated above
$query = mysql_query("SELECT * FROM `table2` WHERE {$SQL}")
I haven't tested the code, but it should work. So, this code will generate SQL like this:
SELECT * FROM `table2` WHERE `id` = '1' OR `id` = '3' OR `id` = '4'
Hope that helps,
spryno724
Most likely you want to join the tables
select
i.Name
from
ProfileInterests p
inner join
interests i
on
p.interestid = i.interestid
where
p.userid = 1

Categories