Can any body help me to convert the following SQL query in LinqToSql syntax. It involves Multiple tables from my tables. I am not sure if I am using correct Query Type. Any help would be highly appreciated.
public IQueryable<tblCourseNeededHours>(int departmentId, string semester)
{
return from =
"SELECT tblCourseNeededHours.Semester, tblCourseNeededHours.NeededHoursPerWeek,
tblCourseNeededHours.AssignToInstituteAdministrator,
tblCourseNeededHours.Freezed, tblCourse.CourseName,
tblInstitute.InstituteName, tblDepartment.DepartmentName
FROM tblCourseNeededHours
INNER JOIN tblCourse ON
tblCourseNeededHours.CourseID = tblCourse.CourseID
INNER JOIN tblInstitute ON
tblCourse.InstituteID = tblInstitute.InstituteID
INNER JOIN tblDepartment ON
tblInstitute.DepartmentID = tblDepartment.DepartmentID";
}
Well, if you have proper foreign keys in your database you can just do
Var x = from nh in db.tblCourseNeededHours
select nh.Semester, nh.xxxx, nh.tblCourse.CourseName,
nh.tbCourse.tblInstitute.CourseName
and so forth.
No need to do any of the inner joins yourself. That is the beauty of Linq2Sql.
Related
I have RATE and BRANCH_CURRE table. I want to perform left join operation (joining branch to rate) in Doctrine Query Language (DQL).
My SQL Query is:
SELECT r.id rid
,r.TIME rtime
,r.rate_candidate
,r.exchange_rate
,r.branch
,r.STATUS ratestatus
,bc.currency
,bc.scale bcscale
,bc.STATUS bcstatus
FROM rate r
LEFT JOIN branch_currency bc ON (
r.branch = bc.branch
AND (
r.from_currency = bc.currency
OR r.to_currency = bc.currency
)
)
WHERE r.STATUS = 1
AND bc.STATUS = 1;
To be more specific, I have two questions here
How to select some specific columns from both the tables.
How to give the multiple ON conditions while joining tables.
So Please show the DQL query using queryBuilder(). Thanx in advance!!!
I suggest to add the additional conditions into a where condition.
Other than that I highly recommend to read the documentation regarding the Doctrine QueryBuilder etc. because you're question does not show that you have any experience with Doctrine at all. Just throwing a MySQL query without any personal effort at us is not a nice and fair way.
This is not tested but should give you some guidance.
$qb = $this->_em->createQueryBuilder();
$qb->select('r.branch, bc.exchange_rate');
$qb->from('rate', 'r');
$qb->leftJoin('r.branch', 'bc');
$qb->where($qb->expr()->orX('r.from_currency=bc.currency','r.to_currency = bc.currency));
I have written a Query,
SELECT dbo.boat.boatno, dbo.boat.boattype, dbo.staff.staffFirstName, dbo.staff.staffLastName,
dbo.branch.branchAddress
FROM dbo.boat INNER JOIN
dbo.BoatOwner ON dbo.boat.OwnerNo = dbo.BoatOwner.OwnerNo INNER JOIN
dbo.branch ON dbo.boat.BranchNo = dbo.branch.branchno INNER JOIN
dbo.staff ON dbo.branch.branchno = dbo.staff.Branchno
WHERE (dbo.branch.branchAddress LIKE '%LONDON%')
But It doesn't work in MYSQL QUERY
How can i convert this into MYSQL QUERY?
You need to know correct table names for MySQL. Assuming a similar structure, I might try:
SELECT b.boatno, b.boattype, s.staffFirstName, s.staffLastName, br.branchAddress
FROM boat b INNER JOIN
BoatOwner bo
ON b.OwnerNo = bo.OwnerNo INNER JOIN
branch br
ON b.BranchNo = br.branchno INNER JOIN
staff s
ON br.branchno = s.Branchno
WHERE br.branchAddress LIKE '%LONDON%';
MySQL does not use the three-part naming that SQL Server does. There is no "schema" in the middle of the name. The additional periods in the column names are probably one source of confusion. Using table aliases should work in both databases and makes the code more readable.
Just a guess from general principles, but perhaps the simpler
SELECT A.boatno, A.boattype, D.staffFirstName, D.staffLastName, C.branchAddress
FROM dbo.boat A, dbo.BoatOwner B, dbo.branch C, dbo.staff D
WHERE B.OwnerNo = A.OwnerNo AND C.branchno = A.BranchNo AND D.Branchno = C.branchno
AND C.branchAddress LIKE '%LONDON%'
may work.
To begin, make sure also that you can SELECT from dbo.boat, dbo.BoatOwner, dbo.branch and dbo.staff using your PHPmyAdmin environment. Sometimes the simple things trip us up...
SELECT b.boatno, b.boattype, s.staffFirstName, s.staffLastName, br.branchAddress
FROM boat b INNER JOIN
BoatOwner bo
ON b.OwnerNo = bo.OwnerNo INNER JOIN
branch br
ON b.BranchNo = br.branchno INNER JOIN
staff s
ON br.branchno = s.Branchno
WHERE br.branchAddress LIKE '%LONDON%';
GROUP BY b.boatno
Isn't that enought?
Is it possible to write this sql query without alias? I am using a PHP script that doesn't covers alias so I have problem with that.
If this is possible please provide me with some help
This is the code:
SELECT
time1.Time, time2.Time, time1.Signal, v.name, v.lastname, k.vehicle, time1.Reg
FROM
data time1
INNER JOIN data time2
ON time1.id != time2.id
AND time1.serial= time2.serial
INNER JOIN drivers v
ON time1.FK_ID_driver=v.ID_driver
INNER JOIN vehicles k
ON time1.Reg=k.Reg
WHERE
TIMEDIFF(time2.Time, time1.Time) BETWEEN '00:15:00' AND '00:30:00';
You can't easily achieve what you want, since you are joining the same table twice, and SQL needs an alias to disambiguate them.
You could, however, create a view for table data, and use the view instead of the table name in one of the data joins.
Example:
select data.time,
vData.time,
data.Signal,
drivers.name,
drivers.lastname,
vehicles.vehicle,
data.Reg
from data
inner join vData on data.id != vData.id and data.serial = vData.serial
inner join drivers on data.FK_ID_driver = drivers.ID_driver
inner join vehicles on data.Reg = vehicles.Reg
where TIMEDIFF(vData.time, data.time) between '00:15:00' and '00:30:00';
I have a question about symfony2.
I have a project and I am using databases with it. I use for the most part Doctrine2 and entity classes. I like the entity class object database stuff, very handy etc.
My question is, is there a way to perform normal SQL in symfony? I always get an exception when I try to use standard SQL. I am having trouble with joins in doctrine2, so i would rather use normal SQL for that.
My join would look like this in SQL:
SELECT DISTINCT Document . *
FROM Document
INNER JOIN DocumentGruppe ON Document.id = DocumentGruppe.dokId
INNER JOIN UserGruppe ON DocumentGruppe.gruppenId = UserGruppe.gruppenId
WHERE UserGruppe.userId =9
The where clause at the end is just for testing. If I use doctrine with it's DQL it always says that there is an exception: The Variable DocumentGruppe was not defined before.
Here is my DQL query:
$test = $em->createQuery(
'SELECT DISTINCT d
FROM AcmeDocumentBundle:Document d
INNER JOIN DocumentGruppe dg ON d.id = dg.dokId
INNER JOIN UserGruppe ug ON dg.gruppenId = ug.gruppenId
WHERE ug.userId =9
'
);
Does anyone know a workaround or a way to use this doctrine2 stuff to work with joins?
Every JOINED tables must be declared as associations in mapping... How is your entity defined ? Show us your mapping file (Document.php if annotation, or Resources/config/doctrine/document;xml or yml if XMl or YAML).
Your request will be something like that :
$test = $em->createQuery(
'SELECT DISTINCT d
FROM AcmeDocumentBundle:Document d
INNER JOIN d.documentGruppen dg
INNER JOIN d.userGruppen ug
WHERE ug.userId =9
'
);
I'm trying to create an "AssociateWith" data load option for my context to filter rows that the current user has access to. My simple data model is as such:
Tables
UserPermissions
PK: ID
FK: RelatedUserID nullable
FK: RelatedItemID not nullable
Users
PK: ID
Items
PK: ID
FK: RelatedCategoryID not nullable
Categories
PK: ID
On my datacontext, I'm trying to do something like:
//dbContext is my LINQ context
//current_user_id is the id of my current logged in user
var dlo = new DataLoadOptions();
//issue->UsersPermissions is one->many relationship
// if I omit this LoadWith line, no associatewith filter
// is created in the generated sql code
dlo.LoadWith<Items>(i=>i.UserPermissions);
dlo.AssociateWith<Items>(i=>
i.UserPermissions.Where(p=>
p.RelatedUserID.HasValue && p.RelatedUserID.Value == current_users_id));
dbContext.LoadOptions = dlo;
Everything seems reasonable to me, but the query generated in SQL looks like this:
SELECT [t0].[ID], [t1].[ID] AS [ID2], [t1].[RelatedUserID], [t1].[RelatedItemID]
(SELECT COUNT(*)
FROM [dbo].[UserPermissions] AS [t2]
WHERE (([t2].[RelatedUserID] = #p0)) AND ([t2].[RelatedItemID] = [t0].[ID])
) AS [value]
FROM [dbo].[Items] AS [t0]
LEFT OUTER JOIN [dbo].[UserPermissions] AS [t1] ON ([t1].[RelatedUserID] = #p0)
AND
([t1].[RelatedItemID] = [t0].[ID])
ORDER BY [t0].[ID], [t1].[ID]
How can I force an INNER JOIN instead of the LEFT OUTER JOIN? Am I modeling my relationship incorrectly on the backend?
Thanks for any help.
MMAS
LINQ to SQL generates the LEFT OUTER JOIN simply because UserPermissions.RelatedUserID column is nullable. The underlying LINQ provider just isn't 'smart' enough to further optimize that query to a simple INNER JOIN. I don't think there is anything you can do about this.