Sql- how to use relational field in condition - mysql

I have three tables which is mapped like this: paymentDetails <-employee<-designation.
Now I have to get datas from paymentDetails table by particular designation of employee..
select *
from paymentDetails
where payment_date=date and employee.designation.desig_id=2;
And I am using Yii2 framework How can I achieve this in Yii2.
I get unknown column error. How to resolve this ?

$command = Yii::app()->db->createCommand()
->select(*)
->from('paymentDetails')
->where('payment_date=date')
->andWhere('employee.designation.desig_id=2')

select *
from paymentDetails
where payment_date=date and employee.designation.desig_id=2;
this will not work in SQL either, it is beacause you are using the tables employee and designation and you do not actually join them in any way.
Now you have not given us any details regarding the name of the models, but it should be something like
$paymentDetails = PaymentDetails::find()->joinWith('employee.designation')-where(['employee.designation.desig_id' => 2, 'payment_date' => 'date'])->all();
This will execute
select *
from paymentDetails JOIN employee ON 'theDefinedRelation' JOIN designation ON 'theSecondDefinedRelation' where payment_date=date and employee.designation.desig_id=2;
Anyway, it will be a long day, if you do not know why the SQL fails you have to learn SQL first.

Related

Yii 2 JSON_VALUE result as join condition in Active Record

Example we have Table A and B.
In table A we have data field with some json data.
How to be build Active Record relation using JSON_VALUE condition?
In plain sql it would look like
SELECT * FROM A
LEFT JOIN B ON B.id = JSON_VALUE(A.data, '$.paramName')
You could use a findBySql method
$sql = "SELECT * FROM A
LEFT JOIN B ON 'B.id = JSON_VALUE(A.data, " . $paramName . ")";
$model = YourModel::findBySql($sql)->all();
As far as i could find framework it self dosnot support sql function execution result as join relation. For now best way for me is to execute subqueries and use populateRelation method. ofcouse if youll find better way i would be glad to know.

Select query in spring hibernate in spring mvc

Hi i am writing an spring mvc, employee application using mysql database,hibernate annotations and jsp . The database contains one table "Empdata" where empid is primary key.And there is a column "team" in "Empdata".I want to select employees in a specific team, example all the details of employees in "Team1".Here i can perform delete and edit operations in the application. For delete operation i am using
sessionfactory.getCurrentSession().createQuery("DELETE FROM Resource WHERE empid=" +resource.getEmpId()).executeUpdate();
query.I know the command line query for select is
SELECT * FROM EmpData WHERE EMPLTEAM ="Team1"
I want to know how to convert this query into hibernate?
please help,thanks in advance..
Query query = session.createQuery("from Resource where emplteam = :team");
query.setParameter("team", "Team1");
List list = query.list();
emplteam should be the property of your class Resource , not your database column's name.
I guess it is simple using HQL .
String hql = "FROM Resource E WHERE E.emplteam = team1";
Query query = session.createQuery(hql);
List results = query.list();
Hope this helps
Note: Keywords like SELECT , FROM and WHERE etc. are not case sensitive but properties like table and column names are case sensitive in HQL.
have you tried using criteria api?
Criteria crit = sessionFactory.getCurrentSession()
.createCriteria(EmpData.class).add(Restrictions.eq("EMPLTEAM", "teamxxx");
List<EmpData> result = crit.list();
For example
Query query = session.createQuery("from Student where name=:name");
query.setParameter("name", "Raj");
In your case i guess the Entity name is Empdata(The object that represent the table)
And the field in the object is team(That has getter and setter in object)
Query query = session.createQuery("from Empdata where team=:teamParam");
query.setParameter("teamParam", "team1");

DetatchedCriteria without on clause

I'm relatively new to Hibernate. I have to use the 3.2 version and i need to use DetachedCriteria and obtain the following query:
select this_.ID as ID0_1_, this_.SNDG as SNDG0_1_
, this_.NDG as NDG0_1_, this_.T_GWR_PARTNER_ID as T4_0_1_
, table2x1_.ID as ID1_0_, table2x1_.T_GWR_PROPOSAL_ID as T2_1_0_
, table2x1_.GROUP_SNDG as GROUP3_1_0_, table2x1_.GROUP_NAME as GROUP4_1_0_
from t_gwr_proposals this_
inner join
t_gwr_proposal_ratings table2x1_
where table2x1_.T_GWR_PROPOSAL_ID=this_.ID
but I obtain the follwing
select this_.ID as ID0_1_, this_.SNDG as SNDG0_1_
, this_.NDG as NDG0_1_, this_.T_GWR_PARTNER_ID as T4_0_1_
, table2x1_.ID as ID1_0_, table2x1_.T_GWR_PROPOSAL_ID as T2_1_0_
, table2x1_.GROUP_SNDG as GROUP3_1_0_, table2x1_.GROUP_NAME as GROUP4_1_0_
from t_gwr_proposals this_
inner join t_gwr_proposal_ratings table2x1_
** on this_.ID=table2x1_.ID **
where table2x1_.T_GWR_PROPOSAL_ID=this_.ID
using this code:
Criteria c = session.createCriteria(T_gwr_proposals.class, "Table1");
c.createAlias("Table1.T_gwr_proposal_ratings", "Table2"); // inner join by default
c.add(Restrictions.eqProperty("Table2.t_gwr_proposal_id", "Table1.proposalsId"));
return c.list();
Can anyone help me, please?
Thank you very much,
Tommaso A.
Criteria doesn't work with tables, but with entities and their association. You can only join two entities via the associations that exist between them. And only one root entity can exist in a criteria query. So, you won't be able to create such a query in Criteria (HQL should do fine, though) unless an association exists between the entities that uses table2x1_.T_GWR_PROPOSAL_ID=this_.ID as its mapping.

NHibernate INNER JOIN on a SubQuery

I would like to do a subquery and then inner join the result of that to produce a query. I want to do this as I have tested an inner join query and it seems to be far more performant on MySql when compared to a straight IN subquery.
Below is a very basic example of the type of sql I am trying to reproduce.
Tables
ITEM
ItemId
Name
ITEMRELATIONS
ItemId
RelationId
Example Sql I would Like to create
Give me the COUNT of RELATIONs for ITEMs having a name of 'bob':
select ir.itemId, count(ir.relationId)
from ItemRelations ir
inner join (select itemId from Items where name = 'bob') sq
on ir.itemId = sq.itemId
group by ir.itemId
The base Nhibernate QueryOver
var bobItems = QueryOver.Of<Item>(() => itemAlias)
.Where(() => itemAlias.Name == "bob")
.Select(Projections.Id());
var bobRelationCount = session.QueryOver<ItemRelation>(() => itemRelationAlias)
.Inner.Join(/* Somehow join the detached criteria here on the itemId */)
.SelectList(
list =>
list.SelectGroup(() => itemRelationAlias.ItemId)
.WithAlias(() => itemRelationCountAlias.ItemId)
.SelectCount(() => itemRelationAlias.ItemRelationId)
.WithAlias(() => itemRelationCountAlias.Count))
.TransformUsing(Transformers.AliasToBean<ItemRelationCount>())
.List<ItemRelationCount>();
I know it may be possible to refactor this into a single query, however the above is merely as simple example. I cannot change the detached QueryOver, as it is handed to my bit of code and is used in other parts of the system.
Does anyone know if it is possible to do an inner join on a detached criteria?
MySql 5.6.5 has addressed the performance issue related to the query structure.
See here: http://bugs.mysql.com/bug.php?id=42259
No need for me to change the output format of my NHibernate queries anymore. :)

How can I optimize this raw SQL and perhaps implement it via CodeIgniter?

It's been a while since I've written raw SQL, I was hoping someone could help me out in optimizing this SQL query so that it works across, both, MySQL and PostgreSQL.
I would also have to implement this via CodeIgniter (2.x) using ActiveRecord, any help/advice?
SELECT *
FROM notaries, contact_notaries
WHERE notaries.id = contact_notaries.notary_id
AND WHERE ( contact_notaries.city LIKE %$criteria%
OR contact_notaries.state LIKE %$criteria
OR contact_notaries.address LIKE %$criteria%)
Thanks!
Each query can have just one WHERE clause (you don't need the second)
It's much better to put join condition into JOIN rather then WHERE.
Are you sure you really need all the columns from 2 tables (*)?
So I'd refactor it to
SELECT [field_list]
FROM notaries
INNER JOIN contact_notaries ON (notaries.id = contact_notaries.notary_id)
WHERE ( contact_notaries.city LIKE '%$criteria%'
OR contact_notaries.state LIKE '%$criteria'
OR contact_notaries.address LIKE '%$criteria%')
Using a1ex07's query:
SELECT [field_list]
FROM notaries
INNER JOIN contact_notaries ON (notaries.id = contact_notaries.notary_id)
WHERE ( contact_notaries.city LIKE '%$criteria%'
OR contact_notaries.state LIKE '%$criteria'
OR contact_notaries.address LIKE '%$criteria%')
Active record:
$this->db->select(); // Leave empty to select all fields
$this->db->join('contact_notaries', 'notaries.id = contact_notaries.notary_id', 'inner');
$this->db->like('contact_notaries.city', 'criteria');
$this->db->like('contact_notaries.state', 'criteria');
$this->db->like('contact_notaries.address', 'match');
$results = $this->db->get('notaries');
To specify a list of fields you can do $this->db->select('field_1, field_2, ...');.
http://codeigniter.com/user_guide/database/active_record.html