mysqli - fetch several rows applying several where conditions - mysqli

With only one query I want to fetch specific rows that contains a range of several string values. Is it possible to modify my WHERE to do this?
This is the code for one country but I want to select several rows for several countries. For example: Jamaica, Portugal and Dominica.
// Select countries to show
$specific_country = Dominica;
// Select and write SPECIFIC ROWS data
$result = mysqli_query($con, "SELECT * FROM $table WHERE Country='$specific_country'");
This will only get the rows of Dominica but I wanted to use something similar to get Jamaica, Portugal and Dominica but all on the same query.

You can use IN()
SELECT *
FROM table_name
WHERE Country IN('Jamaica', 'Portugal', 'Dominica')
Here is SQLFiddle demo
In php
$countries = array('Jamaica', 'Portugal', 'Dominica');
$sql = "SELECT * FROM table_name WHERE Country IN('". implode("','", $countries) . "')";
$result = mysqli_query($con, $sql);
...

Related

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";

getting the 1st row in a database

I want to get the 1st row of the result depends on which build the room is. For example Building 1 have 1-200 rooms and Building 2 have 201-400 rooms. The code I tried is below. I have used the MIN in the where clause but I got all the rooms instead of having one.
$query = $this->db->query("SELECT * FROM `ha_utility_reading`");
if ($query->num_rows == 0) {
echo "some data match";
$lastroom = $this->db->select("*")->from("rooms")
->where("(SELECT MIN(room_num) FROM ha_rooms) and bldg_num = '$bldg_num'")
->get()->result_array();
foreach($lastroom as $key => $test) {
$output['room_num'][] = $test['room_num'];
json_encode($output);
}
You get all the rows because you need a group by clause. Anyway, the best way to do this is just adding this to your query:
order by room_num asc limit 1;
Try this,
select * from rooms order by room_num asc limit 1;

postgresql mathematical formula error

Hi I am trying to use a mathematical function on each row in postgresql.
But It gives me a error.
My Query:
Select
stock_inventory_line.product_code AS Sku,
COUNT(sale_order_line.name) AS Qty_Sold,
stock_inventory_line.product_qty AS Current_Qty,
(stock_inventory_line.product_qty / Qty_Sold) AS NOM
From
sale_order_line,
product_product,
product_template,
product_category,
stock_inventory_line
WHERE
sale_order_line.product_id = product_product.id AND
product_product.product_tmpl_id = product_template.id AND
product_template.categ_id = product_category.id AND
product_product.default_code = stock_inventory_line.product_code
GROUP BY
Sku,
Current_Qty,
NOM;
On this Query It gives me a error: column qty_sold doesn't exist.
If i change the 5th line to
(stock_inventory_line.product_qty / COUNT(sale_order_line.name)) AS NOM
It gives me an error: Aggregate functions not allowed in group by.
You are trying to use COUNT(sale_order_line.name) as a group by item. Aggreagte functions work on grouped item. They are not for grouping them.
I do not know your tables but try
Select
stock_inventory_line.product_code AS Sku,
COUNT(sale_order_line.name) AS Qty_Sold,
stock_inventory_line.product_qty AS Current_Qty,
(stock_inventory_line.product_qty / COUNT(sale_order_line.name)) AS NOM
From
sale_order_line,
product_product,
product_template,
product_category,
stock_inventory_line
WHERE
sale_order_line.product_id = product_product.id AND
product_product.product_tmpl_id = product_template.id AND
product_template.categ_id = product_category.id AND
product_product.default_code = stock_inventory_line.product_code
GROUP BY
stock_inventory_line.product_code,
stock_inventory_line.product_qty;
Basically I remove NOM from the GROUP BY. It is a product for each group, not something you group by.
I run into problems like this all the time. Using a CTE always works for me. Do your aggregations inside the CTE then when you call them in the outer statement, Postgres sees them as numeric instead of aggregations. Your query might run a bit faster too!
Example:
WITH cte AS(
SELECT
sale_order_line.product_id,
stock_inventory_line.product_code,
stock_inventory_line.product_code AS Sku,
COUNT(sale_order_line.name) AS Qty_Sold,
stock_inventory_line.product_qty AS Current_Qty,
(stock_inventory_line.product_qty / Qty_Sold) AS NOM
FROM
sale_order_line,
stock_inventory_line)
SELECT Sku, Qty_Sold, Current_Qty, NOM
FROM
cte,
product_product,
product_template,
product_category
WHERE
cte.product_id = product_product.id AND
product_product.product_tmpl_id = product_template.id AND
product_template.categ_id = product_category.id AND
product_product.default_code = cte.product_code
GROUP BY
Sku,
Current_Qty,
NOM;

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();