I do have 8 tables. when a query fires from search page data from all these 8 tables is pulled out and displayed on the result page. What I want to know is which is the best optimized query method for this process??
what I do now is :
$result = mysql_query("SELECT * FROM TG_dat,TG_dat1,TG_dat2,TG_dat3 WHERE
TG_dat.web = TG_dat1.web AND TG_dat.web = TG_dat2.web AND TG_dat.web =
TG_dat3.web AND TG_dat.web='".$uri."'")or die(mysql_error());
or do i need to use this??
$result = mysql_query("SELECT * FROM TG_dat WHERE web='$uri'")or die(mysql_error());
$result = mysql_query("SELECT * FROM TG_dat1 WHERE web='$uri'")or die(mysql_error());
$result = mysql_query("SELECT * FROM TG_dat2 WHERE web='$uri'")or die(mysql_error());
$result = mysql_query("SELECT * FROM TG_dat3 WHERE web='$uri'")or die(mysql_error());
Your existing query is perfect - always try to use as few queries as possible.
Less calls to the database is generally better, so you can use the first one.
However, rather than putting all of your tables directly into your FROM clause, it's generally considered good practice to use a join on related tables (which it appears these tables are).
For example:
"SELECT *
FROM TG_dat
LEFT JOIN TG_dat2 USING(web)
LEFT JOIN TG_dat3 USING(web)
WHERE TG_dat.web = '$uri'"
Don't worry so much about the two variations in query you've given - they'll perform more or less the same, but if performance is the issue then the first would be my choice - the single query involves a single round-trip to the server and it's easier to handle the results on the client. It's better to concern yourself with the SELECT *, SELECT <the fields you need> would make more sense - you don't need to have the web field returned multiple times in the results.
your existing query is good. The point is to limit querying db server for better effieciency
Related
This question already has answers here:
Which is faster/best? SELECT * or SELECT column1, colum2, column3, etc
(49 answers)
select * vs select column
(12 answers)
Closed 8 years ago.
Lets say I have a table named users with the fields id, name, username, and password. When i write the query for getting all of the fields, is it better to write it this way
$sql = mysqli_query($con,"SELECT * FROM users LIMIT 50");
or this way:
$sql = mysqli_query($con,"SELECT id, name, username, password FROM users LIMIT 50");
for this code:
while($me = mysqli_fetch_array($sql)){
$id = $me['id'];
$name = $me['name'];
$user = $me['username'];
$pass = $me['password'];
}
Is one better then the other. Is one more finely tuned then the other. Or are they both the exact same performance wise
There is no difference in performance at all. I recommend being explicit about the columns that you want to select in production code, however. If you add a column to the table it could have an effect on the query. It's also clearer to anyone maintaining the code what the query is doing and what values are needed.
In point of fact, using SELECT * is less efficient because MySQL will have to look up the column names and it's less memory efficient because the constructs that PHP creates will have more values than are used (possibly) which costs more memory. However, I think this is negligible enough for my "no difference" comment to stand.
I dont know about performance, but when doing joins this can get you into trouble if you have the same column in more than one table. In this case you need to manually alias which will generally require listing all the columns anyhow. Given that i prefer to remain consitent, and as Explosion Pills mentions its easier to tell whats going on/maintain, than using *.
Never use * to return all columns in a table–it’s lazy. You should only extract the data you need. Even if you require every field, your tables will inevitably change.
Fore more detail see this
Is it possible to store the results of a query in a table?
For example, I currently run a query using the following approach in php:
$sql = "SELECT id FROM mytable";
$query = pg_query($connection, $sql);
I then use pg_fetch_row() to access the result and return it to the web-browser. However, I would like to also store the results in a new table. I understand that I could run the same query twice so I would also have:
$sql_2 = "CREATE newtable AS SELECT id FROM mytable";
$query = pg_query($connection, $sql_2);
I was curious if there was a more efficient way of structuring my queries, so that I could both access the results, and insert the results into a table through just one query.
Unfortunately the CREATE TABLE command doesn't appear to accept a RETURNING clause, so that doesn't allow just having that command also return the results. So you're likely to need to do two queries.
You could swap the queries to create the new table first, then fetch the results by selecting out of that new table. Accessing that newly created table may be a bit faster than doing the initial query twice since postgres won't need to look over any irrelevant data. This would also guarantee that the same results appear in both places.
I want to do something like this:
$query=mysql_query("SELECT userid FROM users WHERE username='$username'");
$the_user_id= .....
Because all I want is the user ID that corresponds to the username.
The usual way would be that:
$query=mysql_query("SELECT * FROM users WHERE username='$username'");
while ($row = mysql_fetch_assoc($query))
$the_user_id= $row['userid'];
But is there something more efficient that this?
Thanks a lot, regards
You've hit the nail right on the head: what you want to do is SELECT userid FROM users WHERE username='$username'. Try it - it'll work :)
SELECT * is almost always a bad idea; it's much better to specify the names of the columns you want MySQL to return. Of course, you'll stil need to use mysql_fetch_assoc or something similar to actually get the data into a PHP variable, but at least this saves MySQL the overhead of sending all these columns you won't be using anyway.
As an aside, you may want to use the newer mysqli library or PDO instead. These are also much more efficient than the old mysql library, which is being deprecated.
Not only can you, but you should. Unfortunately too many young developers get in the habit of selecting far too much data. Once you run your query, you don't need to do a while loop since you only have one record coming back. Instead, just use the following:
$sql = sprintf( "SELECT userid FROM users WHERE username = '%s'", $username );
$result = mysql_query( $sql ) or die( mysql_error() );
$data = mysql_result( $result, 0 );
if ( $data ) echo $data; // first userid returned
The second parameter of mysql_result() is the row index you would like to retrieve. 0 is first.
The "usual" way is to only select the columns that you need.
Any column that is part of the select and is not needed will slow down the retrieval. Partly because of network traffic and partly because the database engine can apply certain optimizations if only some columns are selected.
And select * is usually frowned upon in production code.
Your query is correct:
$query = mysql_query("SELECT userid FROM users WHERE username='$username'");
This will work if done correctly. Note that $username must be correctly escaped with mysql_real_escape_string. I'd recommend looking at parameterized queries to reduce the risk of introducing an SQL injection invulnerability.
One other thing you can change is to use mysql_result instead of your loop:
$the_user_id = mysql_result($result, 0);
This assumes that know you'll get only one row.
Yes, that's a great optimization practice!
Also, if you want to go a step further and make it super-optimized, try adding a LIMIT, like this: $query=mysql_query("SELECT userid FROM users WHERE username='$username' LIMIT 1");
This, of course, assumes you expect only one userid to be returned and will make the database engine stop once it finds it.
But, the most important thing: ALWAYS ESCAPE/SANITIZE YOUR INPUT DATA! (can't stress this well enough)
You can do this with a single line of code
echo array_values(mysqli_fetch_array($mysqli->query("SELECT name FROM user WHERE id='$userid'")))[0];
You must connect to the database as shown below before using this
$mysqli = new mysqli('HOST', 'USERNAME', 'PASSWORD', 'DATABASE');
Credits to #samuel t thomas
i am using this query
$query = "SELECT SQL_CACHE * FROM `like` WHERE `id` ='$id' LIMIT 0 , 1";
$result = #mysql_query ($query); // Run the query.
$row = mysql_fetch_array($result);
$crap= $row['crap'];
is there any faster way to execute this query?
i want to execute this as fast as possible
i am using php
thanks
Do you have an index in place on the id column? That's the only way I can think to speed things up.
And maybe selecting only the crap column specifically instead of *.
If this isn't fast enough for you and you control your server infrastructure, you may want to look into caching solutions like Memcache.
That is as simple as youre going to get. This is not what you should be optimizing. It would be better if you optimize all processes leading to this query and after. This is at its optimum state.
If you just need crap column then select only that column that will increase the speed than selecting all. Similarly select only those columns which you need. IF you need all then the query is in its fine state
It should execute as fast as possible, they don't get simpler than this.
I am wondering if there is a possibility.
I have a pagination script that grabs the content from a mysql database with php and using jquery to handle it all.
I want to add a filter to the pagination which will get rid of some content based on the users selection.
When the filter is set I would like the pagination numbers to update to compensate for the items that have been removed.
My biggest concern is that I'm getting the amount of pages to display directly from the database which would make it impossible to update the pagination numbers when filtered:
<?php
include('config.php');
$per_page = 3;
//Calculating no of pages
$sql = "select * from explore";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
$pages = ceil($count/$per_page)
?>
Does anyone know if it is still possible to update these numbers when filtered.
Im mostly using this tutorial in case your wondering:
Here
Just to expand on what Byron said, here is how you do this (based on the code from your link):
Right now in the pagination.php there is a line that looks like this
$sql = "select * from messages";
and in pageination_data.php like this:
$sql = "select * from messages order by msg_id limit $start,$per_page";
Lets say you want a filter that only shows today's messages.
then you would need the following two lines:
$sql = "select * from messages where messages.date = curdate() ";
$sql = "select * from messages where messages.date = curdate() order by msg_id limit $start,$per_page";
of course I expect you will generate the sql statements dynamically in some way. What this allows is the sql server to do the filtering, all the application code stays as you have it.
Note: Remember if you are making dynamic sql to not leave yourself open to sql injection attacks. There are a number of other questions that address sql injection.
The solution is to do the filtration sever side. IE when you apply a filter you send the data to the server and the sql is updated to include/exclude whatever your filter says.