Is it possible to JOIN a subselect with another table in Laravel 5 Query Builder?
I mean - theoretically - something like this:
$sub = DB::table('A')->select(DB::Raw('id, MAX(date)'))->groupBy('id')->get();
$query = DB::table('B')->join($sub, 'B.id', '=', $sub->id)->get();
In my case, in table A I have duplicated rows. I need the ones with max date per id. Then I need to join the result with table B.
As adviced in comments, a workaround follows.
$idArray= DB::table('A')->select(DB::Raw('id, MAX(date)'))->groupBy('id')->lists('id');
$query = DB::table('B')->whereIn('id', $idArray)->get();
But, again, just a workaround.
Related
How Do I do Select Statement in _preparecollection in Magento if the table I joined in the Main table has 2 rows with 1 parent ID.
Tables I have now.
Table 1(Main Table)
Table 2(sales_flat_invoice_comment)
My Current Prepare Collection
$collection = Mage::getResourceModel($this->_getCollectionClass());
$collection->getSelect()->join( array('a'=> mgmx_sales_flat_invoice_comment), 'a.parent_id = main_table.entity_id', array('a.comment'));
$this->setCollection($collection);
return parent::_prepareCollection();
This query, in echoed will be like this
SELECT main_table.*, a.comment
FROM mgmx_sales_flat_invoice_grid AS main_table
INNER JOIN mgmx_sales_flat_invoice_comment AS a
ON a.parent_id = main_table.entity_id
But it will return an error if this query finds more than 1 row in table 2.
What I want is for something like the one below
With | as a delimiter.
How Can I achieved this in the _prepareCollection of Magento.
you have to group by the entity_id and then use group_concat to create your comment column. You can define a separator in the group by.
The concatenated column has a limit in length. So depending on the length of your single comments and the number of comments it might happen that you do not get all of them in the result.
I hope this helps with solving your problem.
To get the group_concat loading in the zend framework you can define it using the Zend_Db_Expr object
Something like
$collection->getSelect()->join(
array('a'=> new Zend_Db_Expr('GROUP_CONCAT(mgmx_sales_flat_invoice_comment)')),
'a.parent_id = main_table.entity_id',
array('a.comment')
);
Which is handy to know about whenever you need to do custom database functions inside the zend framework.
I am attempting to join two tables using the Laravel's query builder however I seem to be having an issue getting the desired result using the query builder, I can however get it quite simply using a raw SQL statement. I simply want to return all mod rows that have the corrosponding value in the tag column in the tags table.
Schema
--------------
mods
--------------
id - int - (primary key)
name - varchar
--------------
tags
--------------
id - int
modid - int - (primary key of its parent mod)
tag - varchar
Working SQL query
SELECT * FROM mod JOIN tags ON tags.tag LIKE '%FPS%'
Query Builder
DB::table('mods')
->join('tags', function ($join) {
$join->on('tags.tag', 'like', '%FPS%');
})
->get();
Currently this is telling me: Unknown column '%FPS%' in 'on clause' but I am unsure how else to structure this. I intend on adding more orOn clauses as well as I will want to get results on multiple tags but firstly I just want to get a single tag working.
Appreciate any help.
SELECT * FROM mod JOIN tags ON tags.tag LIKE '%FPS%'
Your query builder is refusing to generate this query because it's nonsense!
To work correctly, a JOIN clause needs to compare two columns for equality -- one column on each side of the join table. A JOIN clause that doesn't do this is functionally "downgraded" to a WHERE clause. In the case of this query, the two tables end up cross joined.
What you probably want is:
SELECT * FROM mod
JOIN tags ON tags.modid = mod.id
WHERE tags.tag LIKE '%FPS%';
$join->on('tags.tag', 'like', '%FPS%');
Try by replacing
$join->where('tags.tag', 'like', '%FPS%');
This because the on method waiting a name of a field not a query value if you want it to deal with it in this way, you should use DB::raw('%FPS%').
Maybe you are trying to do something like the following:
DB::table('mods')
->select(DB::raw('mods.id as modid, mods.name, tags.id as tagid, tags.tag'))
->join('tags', function ($join) {
$join->on('tags.modid', '=', 'mods.id');
})
->where('tags.tag', 'like', '%FPS%')
->get();
If you want to see what is run in the database use
dd(DB::getQueryLog())
to see what queries were run.
Try this
Thank you
I want to join student_image table with student_details table where
image_id = student_id
but Im stuck here, the query gives the student details, but now I want to add the student image to be displayed together with the student
Below is my query
$query = $this->db->get_where('student_detail',array('reg_no'=>$reg_no))->result_array();
Are you using CodeIgniter?
If you want to display student_image also you can do it like this:
$this->db->select('*');
$this->db->from('student_image a');
$this->db->join('student_details b', 'a.image_id=b.student_detail_id','inner');
$this->db->where('b.student_detail',$reg_no);
return $this->db->get();
or you can do like it this:
$query = "select * from student_image as a join student_details as b on a.image_id=b.student_detail_id where b.student_detail=?"
return $this->db->query($query ,array($reg_no));
I hope this solves your problem
Myself, and probably anyone else has absolutely no idea what that db class you're using is, so we cannot help you with that detail.
A query like this is very basic. A plain query would look somewhat like this:
SELECT *
FROM student_details, student_image
WHERE student_details.studentID = student_image.studentID
And that's it. Now you have to translate it into working with your db class...
I would recommend you learn basic mysql queries before you start using special pre-made classes. They make things a lot more complicated when you do not know what you want it to do yet.
-- The above query will get you the student details only if the row actually exists in both tables.
If you want it back even if it doesn't exist, you could use a LEFT JOIN, like so:
SELECT *
FROM student_details
LEFT JOIN student_image ON student_details.ID = student_image.ID
WHERE student_details.ID = 'myStudentID'
The above query would retrieve a student's results.
Below is my pure SQL query.
SELECT SUM(money) AS total_money, user_id
FROM User
INNER JOIN Person
ON Person.user_id = User.user_id
GROUP BY user_id
How can I convert this pure query into ActiveRecord in Yii framework 2? I could solve the INNER JOIN but don't know how to solve SUM including GROUP BY with Yii 2 ActiveRecord
SELECT part:
use yii\db\Expression;
...
->select([new Expression('SUM(money) as total_money'), 'user_id'])
GROUP BY part:
->groupBy('user_id')
Docs for select() and groupBy() can be found in Query Builder section.
yii\db\Expression is used to prevent quoting.
You can not use sum() method here because it's aggregation method and returns a number, while in your case you use it with other column to return a set of records.
The whole query will look like this:
$personTable = Person::tableName();
$userTable = User::tableName();
$users = User::find()
->select([new Expression('SUM(money) as total_money'), 'user_id'])
->innerJoin($personTable, "$personTable.user_id = $userTable.user_id")
->groupBy('user_id')
->all()
A couple more things to mention:
It's better to use tableName() method to get actual table name instead of writing it manually. In this case if you decide to change table name, you only need to change it in one place.
It's better to replace join part with relation.
$atsum =Atttransactions::find()->select([new \yii\db\Expression('SUM(attt_for_receive) as for_receive')])
->addselect([new \yii\db\Expression('SUM(attt_received) as received')])
->where(['attt_attc_id'=>$modelTran->attt_attc_id])
->asArray()->one();
I have a DB table with product information, and a DB table with tax rates.
My problem is that I am joining these two tables together, which works great.. until I disable "taxable" on a row for the product DB. Now my query is trying to join, but doesn't find a foreign key and I get no result at all.. I want to grab a result either way. I am using code igniter syntax, but it should be pretty obvious whats going on here:
$this->db->from('inventoryTaxRates a');
$this->db->join('inventory_items q', 'q.inventoryTaxRateID = a.inventoryTaxRateID');
sometimes q.inventyTaxRateID becomes 0, or disabled.. The query cannot join the two tables and gives me no result whatsoever. I want it to still give me the result from inventory_items.
I have tried left joining as well:
$this->db->join('inventory_items q', 'q.inventoryTaxRateID = a.inventoryTaxRateID', 'left');
You can specify a RIGHT join like this:
$this->db->join('inventory_items q',
'q.inventoryTaxRateID = a.inventoryTaxRateID',
'right');
You can use RIGHT JOIN, but I'd like to rewrite query like that:
SELECT .. FROM inventory_items ...
LEFT JOIN inventoryTaxRates ...