linQ query joining multiple tables - asp.net-mvc

How do i link 2 tables
Events[ Event_ID , Hobby_Code]
Hobbies[Hobby_Code]
Members[Member_ID,Hobby_Code,Event_ID, Member_Email]
so that when i sent an email to the member the hobby code's of the Members and Events Table must be equal? I want to link Events and Members.

var q = from m in listOfMemebers
join e in listOfEvents on m.Hobby_Code equals e.Hobby_Code
select m;
This will select all the members that have an Hobby_Code that exists on some event

Related

How can I join 2 tables?

I would like to join tables . Could you please help?
Select Number, OwnerId from DNIS.numbers
select ID,Name from DNIS.owners
Thank you.
Normally, SQL servers allow you to join tables from different databases as long as the former all belong to them. Here is an example showing you how to do this (all you have to do is to explicitly write the database names associated to each table in the query):
SELECT N.Number, N.OwnerId, O.ID, O.Name
FROM DB1.[dbo].DNIS numbers N
JOIN DB2.[dbo].DNIS owners O ON O.ID = N.OwnerId
You can also use the following syntax:
SELECT N.Number, N.OwnerId, O.ID, O.Name
FROM DB1..DNIS numbers N
JOIN DB2..DNIS owners O ON O.ID = N.OwnerId
In order to accomplish that you will have to specify the table and column names in your join statement, like so:
SELECT db1.tablename.column, db2.tablename.column
FROM db1.tablename INNER JOIN db2.tablename
ON db1.tablename.id = db2.tablename.id;

Optimizing SQL query using JOIN instead of NOT IN

I have a sql query that I'd like to optimize. I'm not the designer of the database, so I have no way of altering structure, indexes or stored procedures.
I have a table that consists of invoices (called faktura) and each invoice has a unique invoice id. If we have to cancel the invoice a secondary invoice is created in the same table but with a field ("modpartfakturaid") referring to the original invoice id.
Example of faktura table:
invoice 1: Id=152549, modpartfakturaid=null
invoice 2: Id=152592, modpartfakturaid=152549
We also have a table called "BHLFORLINIE" which consists of services rendered to the customer. Some of the services have already been invoiced and match a record in the invoice (FAKTURA) table.
What I'd like to do is get a list of all services that either does not have an invoice yet or does not have an invoice that's been cancelled.
What I'm doing now is this:
`SELECT
dbo.BHLFORLINIE.LeveringsDato AS treatmentDate,
dbo.PatientView.Navn AS patientName,
dbo.PatientView.CPRNR AS patientCPR
FROM
dbo.BHLFORLINIE
INNER JOIN dbo.BHLFORLOEB
ON dbo.BHLFORLOEB.BhlForloebID = dbo.BHLFORLINIE.BhlForloebID
INNER JOIN dbo.PatientView
ON dbo.PatientView.PersonID = dbo.BHLFORLOEB.PersonID
INNER JOIN dbo.HENVISNING
ON dbo.HENVISNING.BhlForloebID = dbo.BHLFORLOEB.BhlForloebID
LEFT JOIN dbo.FAKTURA
ON dbo.BHLFORLINIE.FakturaId = FAKTURA.FakturaId
WHERE
(dbo.BHLFORLINIE.LeveringsDato >= '2017-01-01' OR dbo.BHLFORLINIE.FakturaId IS NULL) AND
dbo.BHLFORLINIE.ProduktNr IN (110,111,112,113,8050,4001,4002,4003,4004,4005,4006,4007,4008,4009,6001,6002,6003,6004,6005,6006,6007,6008,7001,7002,7003,7004,7005,7006,7007,7008) AND
((dbo.FAKTURA.FakturaType = 0 AND
dbo.FAKTURA.FakturaID NOT IN (
SELECT FAKTURA.ModpartFakturaID FROM FAKTURA WHERE FAKTURA.ModpartFakturaID IS NOT NULL
)) OR
dbo.FAKTURA.FakturaType IS NULL)
GROUP BY
dbo.PatientView.CPRNR,
dbo.PatientView.Navn,
dbo.BHLFORLINIE.LeveringsDato`
Is there a smarter way of doing this? Right now the added the query performs three times slower because of the "not in" subquery.
Any help is much appreciated!
Peter
You can use an outer join and check for null values to find non matches
SELECT customer.name, invoice.id
FROM invoices i
INNER JOIN customer ON i.customerId = customer.customerId
LEFT OUTER JOIN invoices i2 ON i.invoiceId = i2.cancelInvoiceId
WHERE i2.invoiceId IS NULL

Unusual Joins SQL

I am having to convert code written by a former employee to work in a new database. In doing so I came across some joins I have never seen and do not fully understand how they work or if there is a need for them to be done in this fashion.
The joins look like this:
From Table A
Join(Table B
Join Table C
on B.Field1 = C.Field1)
On A.Field1 = B.Field1
Does this code function differently from something like this:
From Table A
Join Table B
On A.Field1 = B.Field1
Join Table C
On B.Field1 = C.Field1
If there is a difference please explain the purpose of the first set of code.
All of this is done in SQL Server 2012. Thanks in advance for any help you can provide.
I could create a temp table and then join that. But why use up the cycles\RAM on additional storage and indexes if I can just do it on the fly?
I ran across this scenario today in SSRS - a user wanted to see all the Individuals granted access through an AD group. The user was using a cursor and some temp tables to get the users out of AD and then joining the user to each SSRS object (Folders, reports, linked reports) associated with the AD group. I simplified the whole thing with Cross Apply and a sub query.
GroupMembers table
GroupName
UserID
UserName
AccountType
AccountTypeDesc
SSRSOjbects_Permissions table
Path
PathType
RoleName
RoleDesc
Name (AD group name)
The query needs to return each individual in an AD group associated with each report. Basically a Cartesian product of users to reports within a subset of data. The easiest way to do this looks like this:
select
G.GroupName, G.UserID, G.Name, G.AccountType, G.AccountTypeDesc,
[Path], PathType, RoleName, RoleDesc
from
GroupMembers G
cross apply
(select
[Path], PathType, RoleName, RoleDesc
from
SSRSOjbects_Permissions
where
Name = G.GroupName) S;
You could achieve this with a temp table and some outer joins, but why waste system resources?
I saw this kind of joins - it's MS Access style for handling multi-table joins. In MS Access you need to nest each subsequent join statement into its level brackets. So, for example this T-SQL join:
SELECT a.columna, b.columnb, c.columnc
FROM tablea AS a
LEFT JOIN tableb AS b ON a.id = b.id
LEFT JOIN tablec AS c ON a.id = c.id
you should convert to this:
SELECT a.columna, b.columnb, c.columnc
FROM ((tablea AS a) LEFT JOIN tableb AS b ON a.id = b.id) LEFT JOIN tablec AS c ON a.id = c.id
So, yes, I believe you are right in your assumption

LEFT JOIN Query with JPA not working (select new entity with users that have n documents)

may anybody help me with this task...
persistence provider is eclipselink 2.6.
i want to retrieve a list of users that may have 0 or n documents. because both tables have a few columns i want to use SELECT NEW Entity (userId, amountDocuments), i only need the user-id and the amount of documents for this task. if the user hasn't any documents yet, "0" should be shown, e.g.:
UserId: 1 2 3 4
AmountDocs: 0 1 0 3
Mapping for Documents in Entity User is as follows:
#OneToMany(fetch=FetchType.LAZY, cascade=CascadeType.ALL,mappedBy = "user", targetEntity = UserDocument.class)
#OrderBy("sortOrder ASC")
#JoinFetch(JoinFetchType.OUTER)
protected List<UserDocument>documents;
Mapping for User in Entity UserDocument is as follows:
#ManyToOne(cascade=CascadeType.ALL)
protected User user;
and here is the jpa-query:
SELECT DISTINCT
NEW user.entity.User(u.id,count(doc.user)) FROM User u
LEFT JOIN u.documents doc ON doc.user = u
AND doc.active = 't'
GROUP BY u.id
Problem is, that i only retrieve those two users who have documents that match doc.active='t'.
I also tried it with SIZE(u.documents) which also just returns two users and additionally wrong document-count values.
What is wrong here?
Thanks in advance!
finally after spending hours with that simple stuff, the right solution came with:
SELECT DISTINCT
NEW user.entity.User(u.id,count(doc)) FROM User u
LEFT JOIN u.documents doc ON doc.user = u AND doc.active = 't'
GROUP BY u.id
i have to count the left joined documents itself not the users.

joins on multiple related tables

I have 3 table customer (customerid,name), customerbooking(bookingid,customerid), transact(transacted,bookingid,typeoftransaction)
I want to fetch the name of the ‘customer name’ who has the maximum typeoftransact=’current’. Customer table is linked to customerbooking via customerid, and customerbooking is linked to transact via bookingid. Using join I am able to get the individual records, but unable to get the Max value
Please try this to meet your scenerio
SELECT
C.Name
, Count(BookingID)
FROM Customer C
INNER JOIN customerbooking CB ON CB.CustomerID = C.customerId
INNER JOIN transact T ON T.bookingid = CB.BookingId
WHERE T.Typeoftransaction='current'
GROUP BY C.Name
Hope this helps

Resources