How to print mongodb or mongoose query like mysql? - mongodb

Is there anything similar in mongodb? If we are using dynamic variables and print the query then it should print the query with the values in it like shown below.
int name = 'john';
int age = 23;
// how we do it in PHP
$query = 'select * from students where name='"name"' and age='"age"';
echo $query;
// result
select * from students where name='john' and age='23';
// how we do it in codeigniter
echo $this->db->last_query();
// result
select * from students where name='john' and age='23';

Related

Covert SQL query to TYPO3 query builder?

How to convert SQL query to TYPO3 query builder.
SELECT * FROM tableName ORDER BY (CASE WHEN DATE(dateColumn) < DATE(GETDATE()) THEN 1 ELSE 0
END) DESC, dateColumn ASC
enter link description here
Same functionality i need in typo3 query builder.
To get the sql query you posted, you can do it like following:
// little helper function to debug querybuilder,
// queries with parameter placeholders
function debugQuery(QueryBuilder $builder)
{
$preparedStatement = $builder->getSQL();
$parameters = $builder->getParameters();
$stringParams = [];
foreach ($parameters as $key => $parameter) {
$stringParams[':' . $key] = $parameter;
}
return strtr($preparedStatement, $stringParams);
}
// get querybuilder
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
->getConnectionByName('Default')
->createQueryBuilder();
// build query
$queryBuilder
->select('*')
->from('table')
->getConcreteQueryBuilder()->orderBy(
'(CASE WHEN DATE('
.$queryBuilder->quoteIdentifier('dateColumn')
.') < DATE(GETDATE()) THEN 1 ELSE 0 END)',
'DESC'
)
;
$queryBuilder->addOrderBy('dateColumn', 'ASC');
// build query
$sql = debugQuery($queryBuilder);
The generates following sql query:
SELECT
FROM `table`
ORDER BY
(CASE WHEN DATE(`dateColumn`) < DATE(GETDATE()) THEN 1 ELSE 0 END) DESC,
`dateColumn` ASC
Some note beside:
To my knowlage GETDATE() is not a valid mysql method, more MSSQL. Eventually you want CURRENT_DATE() instead.
edit #1
Not tested/run .. just created the sql string to match what you provided. So don't blame me if provided sql query is wrong itself.

How to search numeric by Sphinx correctly?

I need make search on billion records in MySQL and it's very long process (it's works now). May be Sphinx help me? How correctly to configure Sphinx for search numbers? Should I use integer attribute for searching (not string field)?
I need to get only row where the timestamp 'nearest or equal' to query:
CREATE TABLE test ( date TIMESTAMP(6) UNIQUE, num INT(32) );
| 2018-07-02 05:50:33.084011 | 282 |
| 2018-07-02 05:50:33.084028 | 475 |
...
(40 M such rows... all timestamps is unique, so this column are unique index so I no need in create additional index I suppose.)
sphinx.conf:
source src1
{
type = mysql
...
sql_query = SELECT * FROM test
}
indexer...
Sphinx 3.0.3
...
indexing index 'test'...
collected 40000000 docs, 0.0 MB
In my test I find nearest timestamp to query:
$start = microtime(true);
$query = '2018-07-02 05:50:33.084011';
$connMySQL = new PDO('mysql:host=localhost;dbname=test','','');
$sql = "SELECT * FROM test WHERE date <= '$search' ORDER BY date DESC LIMIT 1";
$que = $connMySQL->query($sql);
$result = $que->fetchAll(PDO::FETCH_ASSOC);
$query = $connMySQL->query('reset query cache');
$connMySQL = null;
print_r ($result);
echo 'Time MySQL:'.(microtime(true) - $start).' sec.';
$start = microtime(true);
$query = '2018-07-02 05:50:33.084029';
$connSphinxQL = new PDO('mysql:host=localhost;port=9306;dbname=test','root','');
$sql = "SELECT * FROM test WHERE date <= '$search' ORDER BY date DESC LIMIT 1";
$que = $connSphinxQL->query($sql);
$result = $que->fetchAll(PDO::FETCH_ASSOC);
$query = $connSphinxQL->query('reset query cache');
$connSphinxQL = null;
print_r ($result);
echo 'Time Sphinx:'.(microtime(true) - $start).' sec.';
Output:
[date] => 2018-07-02 05:50:33.084011 [num] => 282 Time MySQL: 0.00193 sec.
[date] => 2018-07-02 05:50:33.084028 [num] => 475 Time Sphinx: 0.00184 sec.
I suggested to see some different resuts, but noticed that before indexing I have got the same result, so I think Sphinx searches directy in MySQL by the reason of my wrong configuration.
Only ask here I found: no text search
Should I use integer attribute for searching (not string field)?
Yes. But an added complication, is a index NEEDS at least one field (sphinx isnt really designed as a general database, its intended for text queries!)
Can synthesize a fake one.
sql_query = SELECT unix_timestamp(`date`) AS id, 'a' AS field, num FROM test
sql_attr_uint = num
Also shows that need a unique integer as the first column, to be a document_id, seems as your timestamp is unique, can use that. a UNIX_TIMESTAMP is a nice easy way to represent a timestamp as a plain integer.
Can use id in queries too, for filtering, so would need to convert to a timestamp at the same time.
$query = '2018-07-02 05:50:33.084011';
$id = strtotime($query)
$sql = "SELECT * FROM test WHERE id <= '$id' ORDER BY id DESC LIMIT 1";

Zend 2: How do I execute multiple SQL queries using Zend\Db\Adapter?

Im executing this query:
$query = "
Select * From table1 Where id = 1;
Select * From table2 Where name = 'test';
";
With \Zend\Db\Adapter\Adapter:
$stmt = $this->dbAdapter->query($query);
$rawResult = $stmt->execute();
How can I access the second result?
$rawResult->next() only returns values from first query.
Use two different queries.
/*
* First Query
*/
$query = "
Select * From table1 Where id = 1
";
$stmt = $this->dbAdapter->query($query);
$rawResult = $stmt->execute();
/*
* Second Query
*/
$query = "
Select * From table2 Where name = 'test'
";
$stmt = $this->dbAdapter->query($query);
$rawResult = $stmt->execute();
I don't believe it works the way you had it to where two queries in a row are sent this way.
To avoid code duplication you can wrap the duplicated code into a method.
$rawResult1 = $this->getResults("Select * From table1 Where id = 1");
$rawResult2 = $this->getResults("Select * From table2 Where name = 'test'");
function getResults(string $query)
{
$stmt = $this->dbAdapter->query($query);
return $stmt->execute();
}

How to execute union query in zf2 where i m using tablegateway?

How to execute the following query
select * from table1 union select * from table2
in zend-framework2 where i am using tablegateway? In the documentation of zf2,they didn't give any details about union query.
Try -
$select1 = new Select('table1');
[.... rest of the code ....]
$select2 = new Select('table2');
[.... rest of the code ....]
$select1->combine($select2); //This will create the required SQL union statement.
To get count of the two tables you have to use a bit of SQL rather then tableGateway -
$sql = new Sql($this->tableGateway->adapter);
$select_string = $sql->getSqlStringForSqlObject($select1);
$sql_string = 'SELECT * FROM (' . $select_string . ') AS select_union';
$statement = $this->tableGateway->adapter->createStatement($sql_string);
$resultSet = $statement->execute();
$total_records = count($resultSet);
$resultSet gives data.
$total_records gives total no. of records.

how to convert count(*) and group by queries to yii and fetch data from it

I want to convert this query in yii
SELECT count(*) AS cnt, date(dt) FROM tbl_log where status=2 GROUP BY date(dt)
and fetch data from that. I try this command (dt is datetime field):
$criteria = new CDbCriteria();
$criteria->select = 'count(*) as cnt, date(dt)';
$criteria->group = 'date(dt)';
$criteria->condition = 'status= 2';
$visit_per_day = $this->findAll($criteria);
but no data will fetch!
wath can I do to get data?
Probably you see no data because you need assign data to model attributes which doesn't exist.
$criteria = new CDbCriteria();
$criteria->select = 'count(*) AS cnt, date(dt) AS dateVar';
$criteria->group = 'date(dt)';
$criteria->condition = 'status= 2';
$visit_per_day = $this->findAll($criteria);
This means that your model must have attributes cnt and dateVar in order to show your data. If you need custom query then check Hearaman's answer.
Try this below code
$logs = Yii::app()->db->createCommand()
->select('COUNT(*) as cnt')
->from('tbl_log') //Your Table name
->group('date')
->where('status=2') // Write your where condition here
->queryAll(); //Will get the all selected rows from table
Number of visitor are:
echo count($logs);
Apart from using cDbCriteria, to do the same check this link http://www.yiiframework.com/forum/index.php/topic/10662-count-on-a-findall-query/
If you use Yii2 and have a model based on table tbl_log, you can do it in model style like that:
$status = 2;
$result = Model::find()
->select('count(*) as cnt, date(dt)')
->groupBy('date(dt)')
->where('status = :status')
->params([':status' => $status ])
->all();