Drupal 7 select query with joins on entity_id - mysql

I am trying to leftjoin off of the entity_id, but just receiving a error without details.
Is there a trick to leftjoin off of the entity_id in Drupal?
$query = db_query('SELECT COUNT(n.field_feed_vehicle_code_value) FROM {field_data_field_feed_vehicle_code} n LEFT JOIN {field_data_field_feed_vehicle_date_used} du ON n.entity_id = du.entity_id WHERE n.field_feed_vehicle_code_value = :utilization AND du.field_feed_vehicle_date_used = :utilization_date', array(':utilization' => $fieldVehicleCode, ':utilization_date' => $fieldDVIRDate))->fetchField();
I found other questions talking about leftjoins, but nothing really on entity_id. I also found this Drupal 7 select query with joins but this solution did not work either.
$query = db_select('node', 'n');
$query->leftJoin('field_data_field_feed_vehicle_code', 'vc', 'n.nid = vc.entity_id');
$query->leftJoin('field_data_field_feed_vehicle_date_used', 'du', 'n.nid = du.entity_id');
$query
->fields('n', array('nid'))
->fields('vc.field_feed_vehicle_code_value', $fieldVehicleCode , '=')
->fields('du.field_feed_vehicle_date_used', $fieldDVIRDate , '=')
->condition('type', 'dvir_utilization_feed')
->condition('status', 1)
->execute();
$num = $query->rowCount();

I believe that you want to use
->condition('vc.field_feed_vehicle_code_value', $fieldVehicleCode , '=')
->condition('du.field_feed_vehicle_date_used', $fieldDVIRDate , '=')
as that is not the correct syntax for ->fields

I ended up having the wrong field name and had to do db_query, although I would have preferred db_select.
$query = db_query('SELECT COUNT(vc.field_feed_vehicle_code_value)
FROM {node} n
LEFT JOIN {field_data_field_feed_vehicle_code} vc ON n.nid = vc.entity_id
LEFT JOIN {field_data_field_feed_vehicle_date_used} du ON n.nid = du.entity_id
WHERE vc.field_feed_vehicle_code_value = :utilization
AND du.field_feed_vehicle_date_used_value = :utilization_date',
array(':utilization' => $fieldVehicleCode, ':utilization_date' => $fieldDVIRDate))->fetchField();
$utilization = $query;

Related

How do I do this query on codeigniter framework?

I'm kind of new on codeigniter, hope you can help me.
I have a sql query below, how would it look like on codeigniter framework?
SELECT m.conversation_id, count(m.message_id)
FROM cms_conversations__messages AS m
LEFT JOIN cms_conversations__participants AS p ON p.conversation_id = m.conversation_id AND (p.last_read IS NULL OR m.added > p.last_read) AND m.user_id != 2
WHERE p.user_id = 2
GROUP BY p.user_id
Thank you in advance.
If you are sure that your query is right then this is the codeigniter way to do it
$this->db->select('m.conversation_id, count(m.message_id) as message_count');
$this->db->from('cms_conversations__messages as m');
$this->db->join('cms_conversations__participants as p', 'p.conversation_id = m.conversation_id and (p.last_read IS NULL OR m.added > p.last_read) and m.user_id != 2', 'left');
$this->db->where('p.user_id', '2');
$this->db->group_by('p.user_id');
return $this->db->get()->result(); // or you can also store it in a variable
For more you can see the documention.
Hope It helps
As an alternative to using Query Builder you can regular query using query() which supports bound data. (Documented Here)
In your case, it could be done like this.
$sql = "SELECT m.conversation_id, count(m.message_id)
FROM cms_conversations__messages AS m
LEFT JOIN cms_conversations__participants AS p ON p.conversation_id = m.conversation_id
AND (p.last_read IS NULL OR m.added > p.last_read)
AND m.user_id != ? WHERE p.user_id = ? GROUP BY p.user_id";
$id = 2;
$query = $this->db->query($sql, [$id, $id]);
//$query might be FALSE, always check for that before trying to get a dataset
if($query !== FALSE)
{
return $query->result();
}
return FALSE;
The data is bound to the two question marks in the $sql string which gets supplied as the array (i.e. [$id, $id]) in the second argument to query().

Convert raw sql to ZF2 statement

In zf2, how can i write following mysql query and execute it. ??
SELECT * FROM `user_modules` um JOIN ((SELECT vm.id, vm.module_code, vm.module_title,'video' AS type FROM video_master vm WHERE vm.is_deleted = 0) UNION (SELECT sm.id, sm.module_code, sm.module_title, 'slideshow' AS type FROM slideshow_master sm WHERE sm.is_deleted = 0) result ON um.module_id = result.id
WHERE um.user_id='3'
I found solution!!
$userId = '1';
$select = "SELECT * FROM `user_modules` um JOIN ((SELECT vm.id, vm.module_code, vm.module_title, 'video' AS type FROM video_master vm WHERE vm.is_deleted = 0) UNION (SELECT sm.id, sm.module_code, sm.module_title, 'slideshow' AS type FROM slideshow_master sm WHERE sm.is_deleted = 0)) temptable on um.module_id = temptable.id where um.user_id='". $userId ."'";
$resultSet = $this->adapter->query($select);
return $data = $this->resultSetPrototype->initialize($resultSet->execute())->toArray();
OR else can use ZF2 method:
$sql = new Sql($this->getAdapter());
$select = $sql->select()->from(array('um' => $this->table));
Get all slideshow modules
$select1 = $sql->select(array())->from(
array("slideshow" =>'slideshow_master'))
->columns(array('id','module_code','module_title',"type" => new Expression("'Slideshow'")));
$select1 = $sql->select(array())->from(
array("slideshow" =>'slideshow_master'))
->columns(array('id','module_code','module_title',"type" => new Expression("'Slideshow'")));
$select1->where("slideshow.is_deleted = 0");
$select1->order("slideshow.id");
Get all video modules
$select2 = $sql->select(array())->from(
array("video" => 'video_master'))
->columns(
array('id','module_code','module_title',"type" => new Expression("'Video'")));
$select2->where("video.is_deleted = 0");
$select2->order("video.id");
union of two first selects
$select1->combine ( $select2, 'UNION' );
$select->join(array('result' => $select1), "result.id = um.module_id");
$select ->where("um.user_id='". $userId. "'");
$statement = $sql->prepareStatementForSqlObject($select);
return $this->resultSetPrototype->initialize($statement->execute())->toArray();
Sorry for my typing and formatting.

SubQueries in Laravel 4.2

Can anyone teach me how can we use a query like this in Laravel 4.2
SELECT
t.Truck_Number,
t.Created_dt,
t.Latitude,
t.Longitude,
t.Speed,
t.Heading
FROM
truckgps t
INNER JOIN
(
SELECT
Truck_Number,
max(Created_dt) as MaxDate
FROM
truckgps
GROUP BY
Truck_Number
) tm
ON
t.Truck_Number = tm.Truck_Number AND
t.Created_dt = tm.MaxDate
this query is provided by someone else, can it be made better using laravel ?
Using Laravel Query builder - you can make like this :
$results = DB::select("SELECT
t.Truck_Number,
t.Created_dt,
t.Latitude,
t.Longitude,
t.Speed,
t.Heading FROM truckgps t
INNER JOIN
( SELECT Truck_Number, max(Created_dt) as MaxDate from truckgps group by Truck_Number )
tm on t.Truck_Number = tm.Truck_Number and t.Created_dt = tm.MaxDate");
or if you have parameters, than you can binding like this :
DB::select("select count(1) count from table t where t.id= ? and t.roles_id = ?",
array($id, $role_id)
);
If you have two tables...I have one solution for your question.. you dont need use joins for this. Table1 name 'truckgps' and table 2 name 'truckgpss' My Ans
$truckgps = DB::table('truckgps')->select('Truck_Number','Created','Latitude','Longitude','Speed','Heading ')->get();
foreach ($truckgps as $t)
{
$result = DB::table('truckgpss')->select('MAX(Created_dt) AS MaxDate ','Truck_Number')->where('MaxDate','=',$t->Created_dt )->where('Truck_Number','=',$t->Truck_Number)->groupBy('Truck_Number')
->get();
// if u need value convert array to string use another foreach loop here
foreach ($result as $value)
{
echo $value->Truck_Number; // now u can see the result truck no..
}
}
I think its help to u...Thank you ..

How can I implement a multi join in Typo3 via userfunction?

I want to implement the following sql query:
SELECT title
FROM sys_category
JOIN sys_category_record_mm ON sys_category.uid = sys_category_record_mm.uid_local
JOIN tt_content ON sys_category_record_mm.uid_foreign = tt_content.uid
WHERE tt_content.uid = 645
If I execute this query directly via phpmyadmin it is working, but if I try the following via userfunction the content of $row is false, so I think the syntax for my multi join must be wrong. Hope you can help me :)
public function getCategories()
{
$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery
(
'title',
'sys_category JOIN sys_category_record_mm ON sys_category.uid = sys_category_record_mm.uid_local JOIN tt_content ON sys_category_record_mm.uid_foreign = tt_content.uid',
'sys_category.uid = 645'
);
$row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc( $res );
var_dump( $row );
}
My bad, the problem was, that I used
'sys_category.uid = 645'
instead of
'tt_content.uid = 645'

Codeigniter query

My Query :
$this->db->select('*');
$this->db->join('pos_item_sales', 'pos_item_sales.item_id = pos_item_infos.item_id');
$this->db->join('pos_batch_infos', 'pos_batch_infos.item_id = pos_item_infos.item_id');
$this->db->where("`pos_item_sales`.`transaction_id` = '$transaction_id' AND (`pos_item_sales`.`item_barcode` = '$term' OR `pos_batch_infos`.`item_mbarcode` = '$term' OR `pos_item_infos`.`item_id` = '$term')");
$query = $this->db->get('pos_item_infos');
echo $this->db->last_query();
its solve my prob but i need like this query :
$term = $this->input->get('term',TRUE);
$this->db->select('*');
$this->db->join('pos_item_sales', 'pos_item_sales.item_id = pos_item_infos.item_id');
$this->db->join('pos_batch_infos', 'pos_batch_infos.item_id = pos_item_infos.item_id');
$this->db->where('pos_item_sales.transaction_id',$transaction_id);
$this->db->where('pos_item_sales.item_barcode',$term);
$this->db->or_where('pos_batch_infos.item_mbarcode',$term);
$this->db->or_where('pos_item_infos.item_id',$term);
$query = $this->db->get('pos_item_infos');
echo $this->db->last_query();
But I need a Query like :
SELECT *
FROM (`pos_item_infos`)
JOIN `pos_item_sales` ON `pos_item_sales`.`item_id` = `pos_item_infos`.`item_id`
JOIN `pos_batch_infos` ON `pos_batch_infos`.`item_id` = `pos_item_infos`.`item_id`
WHERE `pos_item_sales`.`transaction_id` = '11355822927'
AND (`pos_item_sales`.`item_barcode` = '8801962686156'
OR `pos_batch_infos`.`item_mbarcode` = '8801962686156'
OR `pos_item_infos`.`item_id` = '8801962686156')
how i solve this prob pls help because its not include ( ) in my or condition.
if you go through the codeigniter userguide.. you can see that there are 4 ways to call where clause...
All of these does the same things... and your first code is codeigniter style (if incase you are worried that is not) that is the 4th method by codeigniter userguide where you can write your own clauses manually... there is no difference in calling the where function in anyways...
so i would go with your first query
$this->db->select('*');
$this->db->join('pos_item_sales', 'pos_item_sales.item_id = pos_item_infos.item_id');
$this->db->join('pos_batch_infos', 'pos_batch_infos.item_id = pos_item_infos.item_id');
$this->db->where("`pos_item_sales`.`transaction_id` = '$transaction_id' AND (`pos_item_sales`.`item_barcode` = '$term' OR `pos_batch_infos`.`item_mbarcode` = '$term' OR `pos_item_infos`.`item_id` = '$term')");
$query = $this->db->get('pos_item_infos');
echo $this->db->last_query();
which is perfectly fine...
In cases of complex queries i find it easier to just send raw query like this :
$query = "your query";
$result = $this->db->query($query);
Don't forget to escape variables before inserting them to the query like this :
$var = $this->db->escape($var);
$query="SELECT *
FROM pos_item_infos
JOIN pos_item_sales ON pos_item_sales.item_id = pos_item_infos.item_id
JOIN pos_batch_infos ON pos_batch_infos.item_id = pos_item_infos.item_id
WHERE pos_item_sales.transaction_id = ?
AND (pos_item_sales.item_barcode = ?
OR pos_batch_infos.item_mbarcode = ?
OR pos_item_infos.item_id = ?)";
$params=array();
$params[]='11355822927';
$params[]='8801962686156';
$params[]='8801962686156';
$params[]='8801962686156';
$result=$this->db->query($query,$params);
$result=$result->result_array();
print_r($result);
Also, simplify your syntax with USING.
SELECT *
FROM pos_item_infos
JOIN pos_item_sales USING (item_id)
JOIN pos_batch_infos USING (item_id)
WHERE pos_item_sales.transaction_id = ?
AND (pos_item_sales.item_barcode = ?
OR pos_batch_infos.item_mbarcode = ?
OR pos_item_infos.item_id = ?)