how to combine more than one mysql query into single query - php

i have 3 different queries like below:
$query = "select category_id,category_name from category";
$result = $this->Dbmodel->customQueryResult($query);
$query = "select location,location_name from sub_category";
$result_one = $this->Dbmodel->customQueryResult($query);
$query = "select category_date,category_month from other_category";
$result_two = $this->Dbmodel->customQueryResult($query);
here i am calling mysql server 3 times to execute my query and getting the result thereby..
now i am thinking how can i reduce mysql call so that all these 3 query gets executed in one single query so making only 1 call to mysql server and displaying all different results to user using php
how can i do this.. any help or suggestion would be a great help.. thanks in advance

What you've described is an SQL UNION.
Below is an example query you could use to achieve your goal:
SELECT category_id,category_name FROM category
UNION
SELECT location,location_name FROM sub_category
UNION
SELECT category_date,category_month FROM other_category
Example usage:
$query = 'SELECT category_id, category_name FROM category
UNION
SELECT location, location_name FROM sub_category
UNION
SELECT category_date, category_month FROM other_category';
$result = $this->Dbmodel->customQueryResult($query);
echo 'CategoryID: ' . $result['category_id'] . '<br />';
echo 'Category Name: ' . $result['category_name'] . '<br />';
echo 'Location: ' . $result['location'] . '<br />';
echo 'Location Name: ' . $result['location_name'] . '<br />';
echo 'Category Date: ' . $result['category_date'] . '<br />';
echo 'Category Month: ' . $result['category_month'];
Keep in mind, in case you need to select fields with identical names from different tables to use SQL aliases. An example of an alias:
SELECT category_id AS `catID` FROM category
Instead of $result['category_id'], you would use $result['catID'] instead.

As you are saying none of the tables are related, you have to fetch 3 queries.
You shouldn't combine queries, if there is no any relation. Otherwise it will give you ambiguous data.
We use sub-queries, joins when there is some relation to minimize queries.
Anyways you can get 3 queries result, if 1st, 2nd column have same data type and you can identify from 3rd column it's table name.
SELECT category_id,category_name, 'category' FROM category
UNION
SELECT location,location_name, 'sub_category' FROM sub_category
UNION
SELECT category_date,category_month, 'other_category' FROM other_category

THIS WILL BE EXACT QUERY
$query = "select category.category_id,category.category_name, sub_category.location,sub_category.location_name,other_category.category_date,other_category.category_month from category,sub_category,other_category";
You can use joint properties something like that.
$query = "select * from category, sub_category, other_category";
Note: on *, you can read this question MySQL - specific columns on join?

If the tables are related you could use joins. If that not the case you could use mysql UNION
It would be something like ...
$query = "select category_id,category_name from category UNION select location,location_name from sub_category UNION select category_date,category_month from other_category";

If all 3 Query have same data then we can Combine all 3 queries, Otherwise it would be not useful.
The Other way, Would be as Follows
Select c.category_id, c.category_name,
l.location,l.location_name,
o.category_date,o.category_month
from category C,
sub_category l,
other_category o
But Above would does get the Meaningful Data.

Related

How can I CONCAT fields from different independent tables in MySQL?

I'm getting form data and using it to fetch them individually and then concat. My current query is this:
$design_code = $_POST['design_num'];
$design_code .= ':'.$db->single('SELECT code FROM '. table_brands .' WHERE id=?', [$_POST['brand']]);
$design_code .= ':'.$db->single('SELECT code FROM '. table_types .' WHERE id=?', [$_POST['type']]);
$design_code .= ':'.$db->single('SELECT code FROM '. table_quality .' WHERE id=?', [$_POST['quality']]);
$design_code .= ':'.$db->single('SELECT code FROM '. table_sizes .' WHERE id=?', [$_POST['size']]);
All the POST data are independent and hence cannot be joined. What can be a proper replacement query to merge them in one.
PS: $db->single() basically sends one single field value.
Try this
select (select code FROM table1 where id = 1 ) as code1, (select code FROM table2 where id = 1 ) as code2, table3.code3 FROM table3 where id = 1
The result will get in a single row.
And using UNION query the result will come in more than one row.
EDIT
Update query as per your last comment "Please check: pastebin.com/qGmp8ZKq"
select (select code FROM brand where id = 2 ) as code1, type.code FROM type where id = 6

Codeigniter not showing proper results for array fetched by MySQL query.

I am working with Codeigniter with mysql databases,
I have a model function
public function get_all_data(){
$this->output->enable_profiler(TRUE);
$years = $this->input->post('year');
$months = $this->input->post('month');
$exec_ids = $this->input->post('exec_id');
$query = $this->db->query("SELECT * FROM client_booking AS cb
RIGHT OUTER JOIN executive_client_unit_relation AS ecur ON cb.id = ecur.booking_id
LEFT OUTER JOIN new_invoice ON cb.id = new_invoice.booking_id
WHERE ecur.executive_id IN (" . implode(',', $exec_ids) . ") AND MONTH(cb.booking_date) IN (" . implode(',', $months) . ") AND YEAR(cb.booking_date) IN (" . implode(',', $years) . ")");
return $query->result();
}
The sql generated by this is (as seen in the profiler) :
SELECT * FROM client_booking AS cb
RIGHT OUTER JOIN executive_client_unit_relation AS ecur ON cb.id = ecur.booking_id
LEFT OUTER JOIN new_invoice ON cb.id = new_invoice.booking_id
WHERE ecur.executive_id IN (4,5,6) AND MONTH(cb.booking_date) IN (1,2,3,4,5) AND YEAR(cb.booking_date) IN (2013,2014)
My problem is that the booking_id value is set to NULL when I var_dump() the result of this query.
On the other hand, when I run the SQL in my phpmyadmin, everything goes well and I can see the booking_id
PS: client_booking table's primary key is id which is the booking_id for all the other tables.
Can anyone help me to resolve this?
You are using LEFT/RIGHT joins so when there is no association found between your tables a null row will be returned ,second thing is your tables new_invoice and executive_client_unit_relation both have common names for the column name booking_id and in your select statement you are doing select * so for the columns with same name i guess the last one is picked which is null,for the solution you either you select only needed columns not all like SELECT cb.* or either the columns have same name with your query table then specify them individually with the alias you wish to provide but in the end of select statement in query like SELECT *,cb.id AS booking_id,....

UNION SELECT to get ID's from news and page (A database error occurred: Every derived table must have its own alias)

I'm trying to get the ID's of found items via a custom query. To avoid double results because of searching in 2 tables I understood that I should use UNION.
I wrote this little query:
SELECT * FROM( SELECT `news_item`.`id` as nId, `news_item`.`title`, `news_item`.`content` FROM `news_item` ni UNION SELECT `page_item`.`id` as pId, `page_item`.`title`, `page_item`.`content` FROM `page_item` pi ) WHERE `news_item`.`title` LIKE '%serious%' OR `news_item`.`content` LIKE '%serious%' OR `page_item`.`title` LIKE '%serious%' OR `page_item`.`content` LIKE '%serious%' LIMIT 0, 4
Which results in an SQL error: A database error occurred: Every derived table must have its own alias
I've tried using aliasses(As ni and pi. Also for the select values(ie. ni.title).) and tried without aliases, to no avail.
Here's the PHP:
$searchTerms = array();
foreach($searchWords as $word){
$searchTerms[] = "`news_item`.`title` LIKE '".$word."'";
$searchTerms[] = "`news_item`.`content` LIKE '".$word."'";
$searchTerms[] = "`page_item`.`title` LIKE '".$word."'";
$searchTerms[] = "`page_item`.`content` LIKE '".$word."'";
}
$newsAndPageItemsQry = "
SELECT
*
FROM(
SELECT `news_item`.`id` as nId, `news_item`.`title`, `news_item`.`content` FROM `news_item` ni
UNION
SELECT `page_item`.`id` as pId, `page_item`.`title`, `page_item`.`content` FROM `page_item` pi
)
WHERE
" . implode(" OR ", $searchTerms) . "
LIMIT
" . $scope;
Instant edit: When I give the initial FROM an alias I get the database error: A database error occurred: Unknown column 'news_item.id' in 'field list'. It exists. Definitely.
My question basically: How can I search in page_item and news_item to get the ID's for my keywords in title and content without getting duplicate results?
You say:
Unknown column 'news_item.id' in 'field list'. It exists. Definitely.
But it is not true. Your columns are nId, title and content:
SELECT
`news_item`.`id` as nId, #nId
`news_item`.`title`, #title
`news_item`.`content` #content
FROM `news_item` ni
You should create an alias for subquery:
SELECT
*
FROM(
SELECT `news_item`.`id` as nId, `news_item`.`title`, news_-...
UNION
SELECT `page_item`.`id` as pId, `page_item`.`title`, page_it...
) T <---- here!!!
WHERE
" . implode(" OR ", $searchTerms) . "
LIMIT
" . $scope
Use alias name rather than news_item
Like myAlias.nId=123 or myAlias.title like '%word%'

While loop displaying result 3 times

Basicly I'm trying to make a simple news feed but I'm stuck at the moment as my while loop display the result 3 times, why is this? :/
<?php
$sql ="SELECT
*
FROM
news,
admins";
$result = mysql_query($sql);
if(!$result)
{
echo 'Error while selecting from database. Please contact the administration team';
} else {
while($row = mysql_fetch_assoc($result))
{
echo '
<div class="content_news">
<h1>' . $row['news_name'] . '</h1>
<p style="font-size:12px;">Posted by <b>' . $row['admin_name'] . '</b> on ' . $row['news_date'] . '
<p>' . $row['news_description'] . '</p>
read more
</div>
';
}
}
?>
If you'd like to see what I am talking about: http://freewallpaperblog.com/freshrp/
Ignore the last 2(those are static html not php)
your query selects data from 2 tables (news, admins) so it joins every row of 1st table with every row of 2nd table
SELECT * FROM news, admins
i recommend you to use following query
SELECT news.*, admins.admin_name FROM news
INNER JOIN admins ON news.admin_id = admins.id
where admin_id is your correct column name
You either have 3 admins or 3 rows of news. Your query makes a direct multiplication between tables. Try "left join" instead...
SELECT * FROM news
INNER JOIN admins ON admins.id = news.adminid
Or whatever adminid is in the news table.
Try the following query:
SELECT
*
FROM
news
Inner join admins on news.admin_id = admins.id
You made no JOIN statement in your SQL, as someone else has already commented on in your question. It would help if you posted the associated fields you're grabbing, but based on your $row keys, my best guess is the following should work for you (but I can't promise it will without knowing how your database is designed, I can only infer from the variable names):
$sql = "SELECT news.name, news.date, news.description, news.link, admins.name"
. "FROM news"
. "INNER JOIN admins"
. "ON news.name=admins.name"
References:
http://www.w3schools.com/sql/sql_join_inner.asp
http://www.w3schools.com/sql/sql_join_left.asp
http://dev.mysql.com/doc/refman/5.0/en/join.html

mysql select related terms

I have a table of dictionary terms and now I would like to create another table which would hold ID of the 'main' term and ID of related terms that have the 'main' term's Name included in their Definition -
table: terms
| id | name | definition |
Table: related
| term_id | related_term_id |
It was pretty easy to create INSERT statements in PHP:
$result = mysql_query("SELECT * FROM terms");
while ($row = mysql_fetch_array($result)) {
$name = $row['name'];
$result2 = mysql_query("SELECT id,name FROM terms WHERE description LIKE \"%$name%\" AND id!=".$row['id']);
while ($row2 = mysql_fetch_array($result2)) {
echo "INSERT INTO related(term_id,related_term_id) VALUES(".$row['id'].",".$row2['id'].");";
}
}
However, as I don't have too much experience with MySQL I was wondering if that can be done purely in SQL - let say with use of INSERT-SELECT statement?
Thanks!
INSERT INTO related (term_id, related_term_id)
SELECT a.id as term_id, b.id AS related_term_id
FROM terms a, terms b
WHERE a.id != b.id
AND b.description LIKE CONCAT('%', b.name, '%')
It's going to be real slow if the terms table is big (more than 1000-10000 rows):
INSERT INTO related (term_id, related_term_id)
SELECT describing.id, described.id
FROM terms describing
JOIN terms described
ON CONCAT(' ', described.description, ' ') LIKE CONCAT('% ', describing.name, ' %')
Assuming all descriptions have spaces separating words and no other marks like , or ? or ! or . If that's not the case, the code will be more complicated.
Change your INSERT query:
echo "INSERT INTO related(term_id,related_term_id) VALUES('". $row['id'] ."','". $row2['id'] ."');";

Categories