ReportQuery query =
new ReportQuery.Builder()
.fields(
"CityCriteriaId", "Clicks", "Impressions","Ctr","AverageCpc","AveragePosition","CountryCriteriaId"
)
.from(ReportDefinitionReportType.GEO_PERFORMANCE_REPORT)
.where("CampaignStatus ").in("ENABLED")
.during(ReportDefinitionDateRangeType.LAST_MONTH)
.build();
query is null
ReportQuery query =
new ReportQuery.Builder()
.fields(
"AccountDescriptiveName",
"CampaignName",
"CampaignId",
"CampaignStatus",
"Conversions",
"ConversionRate",
"InteractionRate",
"Interactions",
"Cost",
"Ctr",
"Date",
"Impressions",
"Clicks")
.from(ReportDefinitionReportType.CAMPAIGN_PERFORMANCE_REPORT)
// .where("Status").in("ENABLED")
.during(ReportDefinitionDateRangeType.LAST_30_DAYS)
.build();
query success
Related
I am using QueryBuilder and I need to make a from from SQL function. I am using subqueries, but there is a problem: when I create a SQL query, the round brackets are not created for upc subquery:
qb.leftJoin(
subQuery => {
if (sortOption === TherapistAdminSort.UPCOMING_SESSIONS) {
subQuery
.select('upcoming.id', 'therapistId')
.addSelect('count(*)', 'upcomingSessionsCount')
.from((upc) => {
return upc
.createQueryBuilder()
.select('t.id', 'id')
.addSelect('s.patientId', 'patientId')
.from('therapists', 't')
.withDeleted()
.innerJoin(s => {
return s.select('*')
.from(`get_sessions_by_therapist_id(t.id, now())`, 's2');
}, 's', 's."therapistId" = t.id')
.groupBy('t.id')
.addGroupBy('s."patientId"');
}, 'upcoming')
.groupBy('upcoming.id');
}
return subQuery;
},
'grouped',
'therapist.id = grouped."therapistId"',
)
This query below produces following LEFT JOIN:
LEFT JOIN (SELECT upcoming.id AS "therapistId", count(*) AS "upcomingSessionsCount"
FROM SELECT t.id AS id, s.patientId AS "patientId"
FROM therapists t
INNER JOIN (SELECT * FROM get_sessions_by_therapist_id(t.id, now()) s2) s ON s."therapistId" = t.id
GROUP BY t.id, s."patientId" upcoming
GROUP BY upcoming.id) grouped ON therapist.id = grouped."therapistId"
As you can see, there is no round brackets produced.
Does not work:
$sql = new Sql($this->adapter);
$select = $sql->select();
$select->from('request')
->columns(array('*', new Expression("CONCAT(up1.value,' ',up2.value) as display_name")))
->join(array('up1'=>'user_profile'), "up1.user_id = request.request_user_id AND up1.key = 'user_first_name'", array('up1.value'), 'left')
->join(array('up2'=>'user_profile'), "up2.user_id = request.request_user_id AND up2.key = 'user_last_name'", array('up2.value'), 'left')
;
return $select;
How to make the right?
You specified fields for both joins:
->join(array('up1'=>'user_profile'), "up1.user_id = request.request_user_id AND up1.key = 'user_first_name'", array('up1.value'), 'left')
->join(array('up2'=>'user_profile'), "up2.user_id = request.request_user_id AND up2.key = 'user_last_name'", array('up2.value'), 'left')
When query is converted to actual sql, these fields will be automatically namespaced, so you will get "up1.up1.value" in fields list.
Remove fields references from joins and it should work.
UPD. Right, there's more to it. You can't pass 'user_first_name' as a string value to the "on" parameter of join as it will be interpreted as a column name. So you have to pass an expression:
$select = $sql->select();
$select->from('request')
->columns(array('*', new Expression('CONCAT(up1.value,"#",up2.value) as display_name')));
$expressionString = '? = ? AND ? = ?';
$types = array(Expression::TYPE_IDENTIFIER, Expression::TYPE_IDENTIFIER, Expression::TYPE_IDENTIFIER, Expression::TYPE_VALUE);
$parameters = array('request.user_id', 'up1.user_id', 'up1.key', 'first_name');
$expression1 = new Expression($expressionString, $parameters, $types);
$parameters = array('request.user_id', 'up2.user_id', 'up2.key', 'last_name');
$expression2 = new Expression($expressionString, $parameters, $types);
$select->join(array('up1'=>'user_profile'), $expression1, array('value'), 'left')
->join(array('up2'=>'user_profile'), $expression2, array('value'), 'left');
Y tri to:
$select = $sql->select();
$select->from('request')
->columns(array('*', new Expression('CONCAT(up1.value,"#",up2.value) as display_user_name')));
$expressionString = '? = ? AND ? = ?';
$types = array(Expression::TYPE_IDENTIFIER, Expression::TYPE_IDENTIFIER, Expression::TYPE_IDENTIFIER, Expression::TYPE_VALUE);
$parameters1 = array('request.user_id', 'up1.user_id', 'up1.key', 'user_first_name');
$expression1 = new Expression($expressionString, $parameters1, $types);
$parameters2 = array('request.user_id', 'up2.user_id', 'up2.key', 'user_last_name');
$expression2 = new Expression($expressionString, $parameters2, $types);
$select->join(array('up1'=>'user_profile'), $expression1, array('value'), 'left')
->join(array('up2'=>'user_profile'), $expression2, array('value'), 'left');
does not work, where the error
I am doing like this sql into zend framework sql pattern.
SELECT
jobs . *,
c.id AS cid,
c.name AS name,
c.companyImage AS companyImage,
c.logo AS logo,
count(app.userId) AS t_app,
app.applyStatus AS applyStatus,
app.userId AS appUserId
FROM
jobs
LEFT JOIN
companies AS c ON jobs.companyName = c.id
LEFT JOIN
applicants AS app ON jobs.id = app.jobId AND app.applyStatus = 1
WHERE
jobs.ownerId = 16 AND jobs.draftId != 0
GROUP BY jobs.id
ORDER BY jobs.id DESC
LIMIT 3
For this sql I already write this code for zend framework 2
$adapter = $this->tableGateway->getAdapter();
$sql = new Sql($adapter);
$select = $sql->select();
$select->from('jobs')
->join(array('c' => 'companies'), 'jobs.companyName = c.id', array('cid' => 'id', 'name', 'companyImage', 'logo'), 'left')
->join(array('app' => 'applicants'), ' jobs.id = app.jobId AND app.applyStatus = 1', array('t_app' => new Expression('count(app.userId)'), 'applyStatus', 'appUserId' => 'userId'), 'left')
->where("jobs.ownerId ={$userId} AND jobs.draftId != 0")
->group('jobs.id')
->order('jobs.id DESC')
->limit(3);
$statement = $sql->getSqlStringForSqlObject($select);
$results = $adapter->query($statement, $adapter::QUERY_MODE_EXECUTE);
but does not work properly and its give a message like below.
SQLSTATE[42S22]: Column not found: 1054 Unknown column '1' in 'on clause'
The issue is this part:
app.applyStatus = 1
The framework is escaping 1 as if it were a column name, 1.
You need to enclose this part in an Expression too
new Expression('jobs.id = app.jobId AND app.applyStatus = 1')
I think the use of Expressions in the 'ON' parameter of the join method may depend on the version of ZF2 you are using, I think it was added 2.1+
Building on this answer. If you also want your table & column identifiers to be escaped, use this syntax:
use Zend\Db\Sql\Expression;
...
$onExpression = new Expression('? = ? AND ? = ?',
['jobs.id', 'app.jobId', 'app.applyStatus', 1],
[Expression::TYPE_IDENTIFIER, Expression::TYPE_IDENTIFIER,
Expression::TYPE_IDENTIFIER, Expression::TYPE_LITERAL]
);
$select->from('jobs')
->join(array('app' => 'applicants'), $onExpression, array('t_app' => new Expression('count(app.userId)'), 'applyStatus', 'appUserId' => 'userId'), 'left');
The Expression constructor accepts the string, then arguments, then argument types.
public function __construct($expression = '', $parameters = null, array $types = [])
This will create a security issue. Zf2 changes your query to this:
Select * from tableA inner join tableB
on `tableA`.`column` = `tableB`.`column`
AND `tableB`.`column` = `1`
It adds
`
to each part for security issues! By using new Expression you are bypassing it and if you get applyStatus from user entry, get sure about its filtering!
I am performing a join query with rails with a select however, the result has null id's for the joined table...
#result = Table.joins(:join_table).select(['join_table.id', 'name', 'random_attr', 'created_at']).where('table.random_attr = ?', #anotherresult.id).order('name ASC')
The result...
[
{
random_attr: true
created_at: "2012-10-31T02:23:07Z"
id: null
name: "Joe"
},
....
]
The produced sql looks like...
SELECT join_table.id, name, random_attr, created_at FROM `table` INNER JOIN `join_table` ON `join_table`.`id` = `table`.`user_id` WHERE (random_attr = 9) ORDER BY name ASC;
Doing this query directly in mysql works fine.
I am new bee of Zf2, so please suggest how should I create following sql in Zend framework 2?
Select mt1.*,
(select count(mt2.parent_id)
from md_type as mt2
where mt2.parent_id = mt1.id)) as cnt
from md_type as mt1
You can try this:
$sub = new Select('md_type');
$sub->columns(array(new Expression('COUNT(mt2.parent_id) as total')))
->where(array(
new \Zend\Db\Sql\Predicate\Expression('mt2.parent_id = mt1.id')
))
;
$subquery = new \Zend\Db\Sql\Expression("({$sub->getSqlString()})");
$select = new \Zend\Db\Sql\Select('mt1');
$select->columns(array('*', 'cnt' => $subquery));
this would produce:
SELECT mt1.*,
(SELECT COUNT(mt2.parent_id) as total
FROM "md_type"
WHERE mt2.parent_id = mt1.id
) AS cnt
FROM mt1
Please try this
$sql = new Sql($this->_adapter);
$mainSelect = $sql->select()->from('mt1');
$subQry = $sql->select()
->from('md_type')
->columns(array('orderCount' => new \Zend\Db\Sql\Expression('COUNT(md_type.parent_id)')))
->where('mt2.parent_id = mt1.id');
$mainSelect->columns(
array(
'id',
'total' => new \Zend\Db\Sql\Expression('?', array($subQry)),
)
);
$statement = $sql->prepareStatementForSqlObject($mainSelect);
$comments = $statement->execute();
$resultSet = new ResultSet();
$resultSet->initialize($comments);
return $resultSet->toArray();
Reference: ZF2 - subqueries