php mysql combine queries - php

If I have 2 mysql_query commands in a single php file, is their a way to combine them?
For example, I have:
$a=mysql_query(SELECT * FROM table1);
$b=mysql_query(SELECT id FROM table3);
but I want to combine them into a single mysql_query, would this be more efficient? would it be faster?

multiple queries are not supported in mysql_query as descripted on php manual, so you can't combine both query in php mysql_query way
Here is another good reference from php manual notes:
Executed with multiple queries at
once, the mysql_query function will
return a result only for the first
query. The other queries will be
executed as well, but you won't have a
result for them.

UNION should work (MySQL Manual)
SELECT id FROM table1 UNION SELECT id FROM table3;
Edit:
I see: You want all ("*") from table1. This is a little bit more difficult, but UNION may help also. However, you are really sure you want to do this? Is there any relationship beetween those two tables, or should this just be a kind of micro optimization?

Related

Using Union or run query twice [duplicate]

This question already has an answer here:
Performance/efficiency of 2 SELECT statements vs UNION vs anything else in MySQL-PHP
(1 answer)
Closed 8 years ago.
I have to run a query which retrieves records from two databases. The query is the same for both databases and I use the UNION relationship to just made one query.
The following example will describe what I actually want to do
SELECT col1 FROM db1.table1 UNION SELECT col1 FROM db2.table1 ;
I am using php to execute the above query so I need to know which is better for performance run the above query once or make two queries and merge the results by php
SELECT col1 FROM db1.table1
SELECT col1 FROM db2.table1
please note that I am using a complicated mysql queries which uses regex and sometimes i use subqueries.
Thanks
The only way to be sure is to benchmark it, which I haven't. The following is my best guess about the differences, assuming that:
In both cases there is some post processing in PHP (e.g. printing a result to a browser),
You will always run both queries together (either both are in query cache or none).
If you run them separately you implement the duplicate row removal in PHP.
If there are no duplicate rows:
The union should be faster by a constant amount of time (e.g. 30ms), because of the overhead of running 2 queries instead of one.
If there are duplicate rows:
The union will save you some traffic and PHP processing and might get noticeably faster (if there are a lot of duplicates).

Can I use the result of a previous MySQL query in the From section of another MySQL query?

I'm using a PHP webservice where I have performed a simple SELECT query, and stored it
$result = run_query($get_query);
I now need to perform further querying on the data based on different parameters, which I know is possible via MySQL in the form:
SELECT *
FROM (SELECT *
FROM customers
WHERE CompanyName > 'g')
WHERE ContactName < 'g'
I do know that this performs two Select queries on the table. However, what I would like to know is if I can simply use my previously saved query in the FROM section of the second section, such as this, and if my belief that it helps performance by not querying the entire database again is true:
SELECT *
FROM ($result)
WHERE ContactName < 'g'
You can make a temp table to put the initial results and then use it to select the data and in the second query. This will work faster only if your 1-st query is slow.
PHP and SQL are different languages and very different platforms. They often don't even run in the same computer. Your PHP variables won't interact at all with the MySQL server. You use PHP to create a string that happens to contain SQL code but that's all. In the end, the only thing that counts is the SQL code you sent to the server—how you manage to generate it is irrelevant.
Additionally, you can't really say how MySQL will run a query unless you obtain an explain plan:
EXPLAIN EXTENDED
SELECT *
FROM (SELECT *
FROM customers
WHERE CompanyName > 'g')
WHERE ContactName < 'g'
... but I doubt it'll read the table twice for your query. Memory is much faster than disk.
Thanks for the responses, everyone. Turns out what I was looking for was a "query of query", which isn't supported directly by PHP but I found a function over here which provides the functionality: http://www.tom-muck.com/blog/index.cfm?newsid=37
That was found from this other SO question: Can php query the results from a previous query?
I still need to do comparisons to determine whether it improves speed.
If I understand your question correctly you want to know whether saving the "from" part of your SQL query in a php variable improves the performance of you querying your SQL server, then the answer is NO. Simply because the variable keeping the value is inserted into the query.
Whether performance is gained in PHP, the answer is most probable yes; but depends on the length of the variable value (and how often you repeat using the variable instead of building a new complete query) whether the performance will be notable.
Why not just get this data in a single query like this?
SELECT *
FROM customers
WHERE CompanyName > 'g'
AND ContactName < 'g'

Combining two PHP sql statements into one

I'm after a little help in the quest for cleaner code...
Current code which is working fine. Wondering if I can make it into one SQL statement as opposed to two...
$sql = "INSERT INTO table_a (1,2,3,4) VALUES ('$1','$2','$3','$4');";
$result = mysql_query($sql,$mysql_link);
$id = mysql_insert_id();
$sql2 = "INSERT INTO table_b (1,2,3,4) VALUES ('$id','$5','$6','$7');";
$result2 = mysql_query($sql2,$mysql_link);
How can I combine these two to work within my current php script?
Thanks!
An insert in two different tables is not possible.
If you want to reduce your query count you may have to reconsider your database structure.
As mentioned above, you can't combine them, because inserts are in 2 different tables, although you could write a stored procedure (with necessary parameters) containing both of these queries and call that procedure in PHP instead of writting those statements... It would help to tell the reason you want to do that, because i can't understand if you want to get more compact (reusable) code, or improve the performance of your DB...
When I see another question of this kind, I am always wondering, why noone asks how to combine ALL sql queries of the script into one. All SELECTs, INSERTS, UPDATES. Wouldn't it be logically?
What's the strange desire to combine? What's the point in it? What's wrong in 2 separate queries?
When you eat, do you mix a salad, a soup, a main dish, a drink into one bowl and then consume it? No? Why do you want to put all the queries into same bowl then?

Query a Query - MySQL and PHP

I was recently trying to do a project*, which caused me to ask this question. Although since then I've found an alternative solution, I am still curious if what I envisioned doing is, in any way, possible.
Essentially, I am wondering if there is anyway to perform a MySQL query on a MySQL query result in php. For example:
$result = mysql_query("SELECT * FROM foo WHERE bar=".$barValue);
AND THEN, be able to perform multiple queries on $result:
$newResult = mysql_query("SELECT * FROM $result WHERE otherBar=".$barValue);
OR
$otherNewResult = mysql_query("SELECT * FROM $result WHERE otherOtherBar=".$barValue." ORDER BY foobar ASC");
AND so on and so forth...
I realize that I could append the original query with my new WHERE statements and ORDER BYs, but that causes my to query the database unnecessarily and it prevents me from writing more objected oriented code (because I can't pass around a result to be queried, but rather have to requery the database in every function...)
Any advice, pieces of code, frameworks, or ramblings appreciated.
*BTW, my project was having to query a large database of people for people born in certain age groups and then query those age groups for different demographics.
Edit
No, writing a custom function to query the database is not worth the object-orientation (and modifiability) it would give me
You could do a nested query in the same SQL query and keep PHP out of it:
'SELECT * FROM (SELECT * FROM foo WHERE bar="something") AS q1 WHERE q1.bar2 = "something else"'
The question has already been answered. However following explanation will help someone who might be interested in knowing the details of it.
What are Nested query / subquery:
Subqueries are also known as nested queries. A subquery is a SELECT statement within another statement. MySQL supports all SQL standards and additionally provides MySQL specific features.
Why should I use Subquery:
Subquery is structured and it is possible to isolate each parts of statement
Subquery is more readable that complex joins and unions
Subquery provides alternative means to perform action which otherwise would require complex joins and unions
What Subquery returns:
A subquery can return a single value, a single row, a single column, or a table. These are called scalar, column, row, and table subqueries.
Reference: http://dev.mysql.com/doc/refman/5.7/en/subqueries.html
http://www.w3resource.com/sql/subqueries/nested-subqueries.php

Work-around for PHP5's PDO rowCount MySQL issue

I've recently started work on a new project using PHP5 and want to use their PDO classes for it. The problem is that the MySQL PDO Driver doesn't support rowCount() so there's no way to run a query and then get the number of affected rows, or rows returned, which is a pretty big issue as far as I'm concerned. I was wondering if anyone else has dealt with this before and what you've done to work around it. Having to do a fetch() or fetchAll() to check if any rows were affected or returned seems like a hack to me, I'd rather just do $stmt->numRows() or something similar.
You can issue a SELECT FOUND_ROWS() query right after the original SELECT query to get row count.
$pdo->query("SELECT * FROM users");
$foundRows = $pdo->query("SELECT FOUND_ROWS()")->fetchColumn();
See also: MySQL Docs on FOUND_ROWS()
For those of you who are using MySQL stored procedures, this solution isn't really feasible. What I would suggest that you do is have your stored procedure create two rowsets. The first one will contain one row and one column, containing the number of records. The second will be the recordset you will use for fetching that number of rows.
The number of unlimited rows can be a SELECT COUNT(*) with the exact same WHERE clause as the second rowset without the LIMIT/OFFSET clauses.
Another idea could be to create a temporary table. Use your SELECT statement to populate the temporary table. Then you can use SELECT COUNT(*) FROM tmpTable for your first rowset and SELECT * FROM tmpTable for your second.
This question is based on several false assumptions and one outdated statement.
First of all, do not confuse number of affected and selected rows. PDO supported the former even back in '09.
Speaking of number of rows returned by SELECT statement - you just don't need that number. The data you have is enough.
And yeah, nowadays rowCount() supports number of rows selected from mysql as well. But again - you don't need that number in an average web-application anyway.

Categories