Left Join from Select Zend Framework - mysql

How can I do a Query like this using the Zend framework
SELECT * FROM `productos` AS `p`
LEFT JOIN (SELECT SUM(cantidad) AS transferencias FROM transferencias WHERE upc = p`.`upc` and sucursal = 10)
AS `trans` ON trans.upc = p.upc AND trans.sucursal_clave_destino = 10
Thank you in advance.

You need to try this one.
I can't try it but the way of resolve it you can use from my query
$this->getAdapter()
->select()
->from(array('p' => 'productos'))
->joinLeft(array('trans' => $this->getAdapter()
->select()
->from('transferencias', 'SUM(cantidad)')
->where('upc IN (?)', $this->getAdapter()
->select()
->from('productos', 'upc')
)->where('sucursal = ?', 10)
), 'trans.upc = p.upc')
->where('trans.sucursal_clave_destino = ?', 10)
->query()
->fetchAll();

First of all, I'm afraid it's impossible for your query to run because the syntax is wrong. The correct way to write it is:
SELECT *, SUM(trans.cantidad) as cantidad
FROM productos AS p
LEFT JOIN transferencias AS trans
ON p.upc = trans.upc
WHERE trans.sucursal_clave_destino = 10 AND trans.sucursal = 10
First approach
I assume you have created your model in this manner: http://framework.zend.com/manual/1.12/en/learning.quickstart.create-model.html
For example, in your Default_Model_ProductosMapper:
function getXXXX(){
$select = "[THE ABOVE QUERY]";
$result = $this->getDbTable()->getAdapter()->fetchAll($select);
return $result;
}
This is the most basic approach.
Second approach
By using Zend_Db functions, which is like prepare statement in database concept. Only use it to increase safety if you are passing parameters from user input (see SQL injection), otherwise it's safe to use the first approach.
Still, in your mapper:
function getXXXX(){
$query = $this->getDbTable()->getAdapter()->select();
$query->from('productos', array());
$query->joinLeft('transferencias', 'productos.upc = transferencias.upc', array('SUM(trans.cantidad) as cantidad));
$query->where("trans.sucursal_clave_destino = 10");
$query->where("trans.sucursal = 10");
// get result
$stmt = $this->getDbTable()->getAdapter()->query($query);
$result = $stmt->fetchAll();
return $result;
}
Third approach
If you are using Database ORM like Doctrine2, you can also write SQL or DQL (Doctrine Query Language) queries, which syntax is highly similar with SQL queries but absolutely NOT the same mechanism. The document is here. This document covers both approaches above for DQL and also will tell you where to put them.

Related

MySQL optional filters for search query

I am working on a query that has an optional filter, so lets assume the table name is products and the filter is the id (primary key)
If the filter is not present I would do something like this:
SELECT * FROM products;
If the filter is present I would need to do something like this:
SELECT * FROM products WHERE id = ?;
I have found some potential solutions that can mix the 2 in sql rather than doing conditions in the back-end code itself
SELECT * FROM products WHERE id = IF(? = '', id, ?);
OR
SELECT * FROM products WHERE IF(? = '',1, id = ?);
I was just wondering which one would be faster (In the case of multiple filters or a very big table) Or is there a better solution to handle this kind of situation?
A better approach is to construct the WHERE clause from the parameters available. This allows the Optimizer to do a much better job.
$wheres = array();
// Add on each filter that the user specified:
if (! empty($col)) { $s = $db->db_res->real_escape_string($col);
$wheres[] = "collection = '$s'"; }
if (! empty($theme)) { $s = $db->db_res->real_escape_string($theme);
$wheres[] = "theme = '$s'"; }
if (! empty($city)) { $s = $db->db_res->real_escape_string($city);
$wheres[] = "city = '$s'"; }
if (! empty($tripday)) { $s = $db->db_res->real_escape_string($tripday);
$wheres[] = "tripday = '$s'"; }
// Prefix with WHERE (unless nothing specified):
$where = empty($wheres) ? '' :
'WHERE ' . implode(' AND ', $wheres);
// Use the WHERE clause in the query:
$sql = "SELECT ...
$where
...";
Simplest approach is OR:
SELECT *
FROM products
WHERE (? IS NULL OR id = ?);
Please note that as you will add more and more conditions with AND, generated plan will be at least poor. There is no fit-them-all solution. If possible you should build your query using conditional logic.
More info: The “Kitchen Sink” Procedure (SQL Server - but idea is the same)

Codeigniter - how to delete row on inner join? [duplicate]

I have a problem with my query and I need to join two tables from different databases now my problem is how can I execute my query. I got my syntax format from here
Please visit first this link so you could understand why my SQL syntax is like this http://www.x-developer.com/php-scripts/sql-connecting-multiple-databases-in-a-single-query
Im using CodeIgniter and here is an Idea of what my query looks like: Notice the way I'm selecting my columns: DATABASE_NAME.TABLE_NAME.COLUMN_NAME
$ENROLLEES = $this->load->database('ENROLLEES', TRUE);
$ACCOUNTS = $this->load->database('ACCOUNTS', TRUE);
$SELECT = "SELECT $ACCOUNTS.BALANCES_TABLE.IDNO, $ACCOUNTS.BALANCES_TABLE.balance";
$FROM = "FROM $ACCOUNTS.BALANCES_TABLE";
$WHERE = "$ACCOUNTS.BALANCES_TABLE.IDNO IN (SELECT $ENROLLEES.ENROLLEES_TABLE.IDNO FROM $ENROLLEES.ENROLLEES_TABLE)";
$SQL = $SELECT ." ". $FROM ." ". $WHERE;
MAIN PROBLEM: How to Execute my query?
If we do like this in codeIgniter:
$ENROLLEES->query($SQL); or $ACCOUNTS->query($SQL);
How can I execute my query that Im having multiple databases? What will I provide here[database]->query($SQL); ?
$sql="Select * from my_table where 1";
$query = $this->db->query($SQL);
return $query->result_array();
If the databases share server, have a login that has priveleges to both of the databases, and simply have a query run similiar to:
$query = $this->db->query("
SELECT t1.*, t2.id
FROM `database1`.`table1` AS t1, `database2`.`table2` AS t2
");
Otherwise I think you might have to run the 2 queries separately and fix the logic afterwards.
I can see what #Þaw mentioned :
$ENROLLEES = $this->load->database('ENROLLEES', TRUE);
$ACCOUNTS = $this->load->database('ACCOUNTS', TRUE);
CodeIgniter supports multiple databases. You need to keep both database reference in separate variable as you did above. So far you are right/correct.
Next you need to use them as below:
$ENROLLEES->query();
$ENROLLEES->result();
and
$ACCOUNTS->query();
$ACCOUNTS->result();
Instead of using
$this->db->query();
$this->db->result();
See this for reference:
http://ellislab.com/codeigniter/user-guide/database/connecting.html
http://www.bsourcecode.com/codeigniter/codeigniter-select-query/
$query = $this->db->query("select * from tbl_user");
OR
$query = $this->db->select("*");
$this->db->from('table_name');
$query=$this->db->get();
return $this->db->select('(CASE
enter code hereWHEN orderdetails.ProductID = 0 THEN dealmaster.deal_name
WHEN orderdetails.DealID = 0 THEN products.name
END) as product_name')
$this->db->select('id, name, price, author, category, language, ISBN, publish_date');
$this->db->from('tbl_books');

Codeigniter multi select query

I have tried to make codeigniter query from mysql query
my mysql query is:
select *
from class_routine
where
semester='$semester'
and day='$day'
and time_schedule='$time_schedule'
and (batch='$batch' or section='$section' or teacher='$teacher' or room='$room');
for above query what will be the codeigniter query ?
I will use this query in model.
First, you should consider looking at the Documentation before asking any question, then specify what you've looked at and what you did try, posting your code.
Anyways, try this and let me know:
$this->db->where(array('semester' => $semester, 'day' => $day, 'time_schedule' => $time_scehdule));
$this->db->where("batch = $batch OR section = $section OR teacher = $teacher OR room = $room", NULL, FALSE);
$result = $this->db->get('class_routine')->result();
When in doubt is perfectly safe to use a normal query:
$result = $this->db->query("SELECT * FROM ....")->result();

How to run raw SQL Query with Zend Framework 2

Is there a way to execute a SQL String as a query in Zend Framework 2?
I have a string like that:
$sql = "SELECT * FROM testTable WHERE myColumn = 5"
now I want to execute this string directly.
Just pass the sql string to your db adapter like this:
$resultSet = $adapter->query($sql, \Zend\Db\Adapter\Adapter::QUERY_MODE_EXECUTE);
And if you want to pass parameters:
$sql = "SELECT * FROM testTable WHERE myColumn = ?";
$resultSet = $adapter->query($sql, array(5));
EDIT: Please note that the query method does not always returns a resultset. When its a resultset producing query(SELECT) it returns a \Zend\Db\ResultSet\ResultSet otherwise(INSERT, UPDATE, DELETE, ...) it will return a \Zend\Db\Adapter\Driver\ResultInterface.
And when you leave the second Parameter empty you will get a \Zend\Db\Adapter\Driver\StatementInterface which you can execute.
use Zend\Db\Sql\Sql;
use Zend\Db\Adapter\Adapter;
$dbAdapterConfig = array(
'driver' => 'Mysqli',
'database' => 'dbname',
'username' => 'dbusername',
'password' => 'dbuserpassword'
);
$dbAdapter = new Adapter($dbAdapterConfig);
$sql = new Sql($dbAdapter);
$select = $sql->select();
$select->from('testTable');
$select->where(array('myColumn' => 5));
$statement = $sql->prepareStatementForSqlObject($select);
$result = $statement->execute();
S. docu: Zend\Db → Zend\Db\Sql
If you are using tableGateway, you can run your raw SQL query using this statement,
$this->tableGateway->getAdapter()->driver->getConnection()->execute($sql);
where $sql pertains to your raw query. This can be useful for queries that do not have native ZF2 counterpart like TRUNCATE / INSERT SELECT statements.
If you have EntityManager $em on your hands, you can do something like this:
$select = $em->getConnection()->executeQuery("
SELECT a.id, a.title, a.announcement, asvc.service_id, COUNT(*) AS cnt,
GROUP_CONCAT(asvc.service_id SEPARATOR \", \") AS svc_ids
FROM article AS a
JOIN articles_services AS asvc ON asvc.article_id = a.id
WHERE
asvc.service_id IN (
SELECT tsvc.service_id
FROM tender AS t
JOIN tenders_services AS tsvc ON tsvc.tender_id = t.id
WHERE t.id = :tenderId
)
GROUP BY a.id
ORDER BY cnt DESC, a.id DESC
LIMIT :articlesCount
", [
'articlesCount' => 5,
'tenderId' => $tenderId,
], [
'articlesCount' => \PDO::PARAM_INT,
]);
$result = $select->fetchAll(); // <-- here are array of wanted rows
I think this way to execute complex queries is best for Zend. But may be I'm not very smart in Zend still. Will glad to see if it helps to someone.

Question mark DQL is not considered?

I have the following DQL query:
$query = Doctrine_Query::create()
->select('p.genre')
->from('Profile p')
->where('sf_guard_user_id = ?', 11);
If I return the SQL syntax with $sql = $query->getSqlQuery(); I get:
SELECT p.id AS p__id, p.genre AS p__genre FROM profile p WHERE (p.sf_guard_user_id = ?)
This is not normal. It should be 11 not ?:
SELECT p.id AS p__id, p.genre AS p__genre FROM profile p WHERE (p.sf_guard_user_id = 11)
And if I write:
$query = Doctrine_Query::create()
->select('p.genre')
->from('Profile p')
->where('sf_guard_user_id = ' . 11);
The SQL syntax is correct.
Normally DQL should do this automatically. Why isn't happening ?
This is how prepared statement works. Values will be bound on database server Hence doctrine can not show the real values with the query.
Doctrine will show a question mark if you use prepared statement not the real value.
Checkout how it is describing here