So my question is:
Is it possible to select all data from different tables in one query?
Example1:
$query = $this->db->get('table1');
$query = $this->db->get('table2');
$query = $this->db->get('table3');
return $query->result();
Example2:
$this->db->select('*');
$this->db->from('table1', 'table2', 'table3');
$query = $this->db->get();
return $query->result();
I think the second exaple is possible. If not i want to ask how you would do that.
Thank you.
It can be done by putting the table names in an arrary
$query = $this->db
->select('*')
->from(['table1', 'table2'])
->get();
return $query->result();
But the number of rows in the result will be the product of the number of rows in each table, i.e. table1 has 3 rows and table2 has 19 you'll get 57 rows in the result. Are you sure that's what you want?
Joins are easy to write and highly efficient. Don't be afraid of them.
Related
I have a codeigniter-mysql requirement to select values from table_2 which joins table_1 and need to apply where statement in a comma separated field value. Tried as follows,
$where = $this->db->escape("FIND_IN_SET(table_1.id,table_2.places_id)<>0");
$this->db->select('table_2.*,GROUP_CONCAT(table_1.location)AS location');
$this->db->from('table_2');
$this->db->join('table_1', $where);
$this->db->where('ltable_2.packages_id', $id);
$results = $this->db->get();
return $results->result();
But the above codeigniter db object returns following mysql query and its not working :(
SELECT `table_2`.*, GROUP_CONCAT(table_1.location)AS location FROM `table_2` JOIN `table_1` ON 'FIND_IN_SET(table_1.id,table_2.places_id)<>0' WHERE `ltable_2`.`packages_id` = <id-goes-here>
It seems the quotes around 'FIND_IN_SET(table_1.id,table_2.places_id)<>0' creates the problem! All helps are appreciated to resolve the issue.
You could try $this->db->join('table_1', $where, false);. That would get rid of the quotes, and if otherwise your query is good, it should be fine.
I need to filter duplicates, but union is displaying duplicates.
For example Query-1 is displaying 5 tuples like 1,2,3,4,5.
Query-2 generating 3 tuples like 1,2,6.
Union of both the tuples displaying result 1,2,3,4,5,1,2,6.
But I want the result as 1,2,3,4,5,6.
Here is my controller :
public function product()
{
$product = $this->input->post('keyword');
$temp = explode(" ", $product);
$count = count($temp);
for($i=0;$i<$count;$i++)
{
$query = "SELECT * FROM `product` WHERE SOUNDEX(`name`) LIKE CONCAT('%',SOUNDEX('$temp[$i]'),'%') UNION SELECT * FROM `product` WHERE `name` like '%$temp[$i]%'";
$data = $this->Back_model->getby_query($query);
$records = json_encode($data);
echo $records;
}
}
There is no apparent reason for using 2 select queries, the second filter may be added to an existing where clause
SELECT *
FROM `product`
WHERE SOUNDEX(`name`) LIKE CONCAT('%',SOUNDEX('$temp[$i]'),'%')
AND `name` like '%$temp[$i]%'";
First of all, I would probably do this in another scripting language, but if you really want to do this in MySQL, you need to use DISTINCT. You should query the data and put it in a temp table, and from the temp table query the DISTINCT values. Once you're done you can drop the temp table. For an operation this small, not sure if this is what I would do, but if you say that you have thousands of records/values that need to be filtered, than it might be worth it.
I've a db that have 2 tables, and a search keyword, how can i join the tables, to do the select's in all the tables?
$this->db->select('*');
$this->db->from('tracks', 'genres');
$this->db->join('genres', 'genres.genreid = tracks.genre_id');
$this->db->or_where('tracks.title', $key);
$this->db->or_where('tracks.author', $key);
$this->db->or_where('genres.genreid', $key);
$this->db->order_by('tracks.rate', 'ASC');
$q = $this->db->get();
you have to have one table in from and the rest in the join
$this->db->from('tracks');
It also pays to use the join statement to do the job of your where clause(s). If you do join and then where it selects all of the join between the tables and then applies where, but with ANDs in the join, there's less work to be done for the db.
$this->db->select('*');
$this->db->from('tracks');
$this->db->join('genres', 'genres.genreid = tracks.genre_id');
$this->db->where('tracks.title', $key);
$this->db->or_where('tracks.author', $key);
$this->db->or_where('genres.genreid', $key);
$this->db->order_by('tracks.rate', 'ASC');
$q = $this->db->get();
This is the correct way of using it. You are using same table in FROM clause and JOIN this is problem. Another thing is that you are missing WHERE clause and only using or where.
I have a simple pdo prepared query:
$result = $db->prepare("select id, course from coursescompleted where person=:p");
$result ->bindParam(':p', $q, PDO::PARAM_INT);
$result->execute();
$rows = $result->fetch(PDO::FETCH_NUM);
echo $rows[0];
the echo seems to be returning the ID value of the record, not the number of records returned by the query?
any idea or explanation for this?
You've executed a query that returns rows from the database, fetched the first row from the result into a variable and then echo'd the first column of that row.
If you want to count, do an SQL count()
$result = $db->prepare("select count(*) from coursescompleted where person=:p");
$result->bindParam(':p', $q, PDO::PARAM_INT);
$result->execute();
$rowCount = $result->fetchColumn(0);
echo $rowCount;
PDO::FETCH_NUM: returns an array indexed by column number as returned in your result set, starting at column 0
You aren't fetching the row-count at all.
SELECT COUNT(*) FROM coursescompleted where person=:p
This query would return total rows in $rows[0];
EDIT:
Please see #ray's answer. using count(id) is better than count(*) for InnoDB.
You could get row-count in the following manner, from your earlier query.
$row_count = $result->rowCount();
But be warned:
If the last SQL statement executed by the associated PDOStatement was
a SELECT statement, some databases may return the number of rows
returned by that statement. However, this behaviour is not guaranteed
for all databases and should not be relied on for portable
applications.
Documentation
Assuming id is the primary key use:
SELECT COUNT(id) FROM coursescompleted WHERE person=:p;
Avoid a count(*). If your storage engine is InnoDB (possibly others except MyIsam) you'll take a performance hit.
Try echo count($rows); as $rows is an array.
Edit:
To use the results
$rows = $result->fetchAll(/* nothing here */);
if(count($rows) > 0) {
// Show results, perhaps using a foreach($rows as $row)
} else {
echo "Sorry, no results found";
}
You can use this
<?php
$result = $db->prepare("select id, course from coursescompleted where person=:p");
$result ->bindParam(':p', $q, PDO::PARAM_INT);
$result->execute();
$rows = $result->rowCount();
echo $rows;
?>
This sometimes does not work on SELECT queries. But based on personal experience, and since you didn't mention porting it to other database systems, it should work on MySQL.
More info is in PHP manual here
I am running a query to populate a dropdown menu, however the column I am using a list of company names, this means that the company name is often repeated, is there way to only get each repeated value only once? So for instance if I have in the table something like,
Company 1
Company 1
Company 2
Company 3
Company 4
Company 4
But I would like the dropdown to return,
Company 1
Company 2
Company 3
Company 4
I am using the database libray and active record to write the sql like this currently I need to know what I use to only show each result once,
function getAllUsers() {
$this->db->select('*');
$this->db->from('userProfileTable');
$query = $this->db->get();
return $query->result_array();
}
Or what would the raw sql be?
Use:
$this->db->distinct();
$this->db->select('*');
$this->db->from('userProfileTable');
$query = $this->db->get();
return $query->result_array();
You can use $this->db->distinct(); which adds the DISTINCT keyword to your query.
Modify your function to this:
function getAllUsers() {
$this->db->distinct();
$query = $this->db->get('userProfileTable');
return $query->result_array()
}
which produces
SELECT DISTINCT * FROM userProfileTable
Please note that select and from have been removed from your original function because get simply does the same thing.
Use DISTINCT keyword:
SELECT DISTINCT * from userProfileTable;
This should do the trick:
function getAllUsers() {
$this->db->distinct();
$query = $this->db->get('userProfileTable');
return $query->result_array();
}