I am new in MVC. Linq is the system of making queries in database. but I am having difficulties right now with Linq. Anyone know how to convert my sql statement to Linq?
My entities, seperate context
localDB.summaries
accountDB.account
SELECT * FROM summary
WHERE studentID =
(SELECT studentID FROM accounts WHERE username = 'username123')
FROM user IN localDB.summaries
WHERE -------- please guide my linq--------
SELECT user
At a guess without knowing your entities:
var query = from user in localDB.summaries
join account in localDB.accounts on user.studentID equals account.studentID
where account.username == "username123"
select user;
I am assuming that accounts table has been mapped with student on the basis of student id I mean there is a foreign key relationship so by assuming that:
var data = localDB.summaries.where(c=>c.Students.Account.FirstorDefault().username == "username123")
Related
I have two tables, Users and Relationships tables. Users table has following columns:
id, name,password,username,email,avatar,followersCount,followingCount,tweetCount.
And the Relationships table has the following columns:
id, followingId, followerId
How should I go about creating a SQL query to extract a user with a specific Id and find id's from Relationships that user is following? So in other words find people that user follows
I've come this far so long
SELECT *
FROM public."Users" JOIN
public."Relationships"
ON (public."Users".id = public."Relationships".id)
If I understand correctly, you want:
SELECT u.*
FROM public."Relationships" r JOIN
public."Users" u
ON u.id = r.followerId
WHERE r.followingId = ?;
? is a parameter placeholder for the user you care about. This returns all the followers of that user.
Do you mean this query
SELECT public."Users".*
FROM public."Users"
JOIN public."Relationships"
ON public."Users".id = public."Relationships".followingId
AND public."Relationships".followerId = a user ID
I am not really clear about followerId and followingId mean but you can change them in the query if it is not what you want.
Sorry if that title is a bit convoluted... I'm spoiled by an ORM usually and my raw SQL skills are really poor, apparently.
I'm writing an application that links to a vBulletin forum. Users authenticate with their forum username, and the query for that is simple (selecting by username from the users table). The next half of it is more complex. There's also a subscriptions table that has a timestamp in it, but the primary key for these is a user id, not a username.
This is what I've worked out so far:
SELECT
forum.user.userid,
forum.user.usergroupid,
forum.user.password,
forum.user.salt,
forum.user.pmunread,
forum.subscriptionlog.expirydate
FROM
forum.user
JOIN forum.subscriptionlog
WHERE
forum.user.username LIKE 'SomeUSER'
Unfortunately this returns the entirety of the subscriptionlog table, which makes sense because there's no username field in it. Is it possible to grab the subscriptionlog row using the userid I get from forum.user.userid, or does this need to be split into two queries?
Thanks!
The issue is that you are blindly joining the two tables. You need to specify what column they are related by.
I think you want something like:
SELECT * FROM user u
INNER JOIN subscriptionlog sl ON u.id = sl.userid
WHERE u.username LIKE 'SomeUSER'
select * from user u JOIN subscriptions s ON u.id = s.id where u.username = 'someuser'
The bit in bold is what you want to add, it combines the 2 tables into one that you return results from.
try this
SELECT
forum.user.userid,
forum.user.usergroupid,
forum.user.password,
forum.user.salt,
forum.user.pmunread,
forum.subscriptionlog.expirydate
FROM
forum.user
INNER JOIN forum.subscriptionlog
ON forum.subscriptionlog.userid = forum.user.userid
WHERE
forum.user.username LIKE 'SomeUSER'
Early last year I was on a project using Oracle DB and was introduced to a new querying format where you could query the results of the previous query. It was only for a few weeks we were helping on the project so so I don't recall exactly how things were written. But, it was something like the outline below. Note all of the query I believe was written in a stored procedure and in just 1 procedure. Forgive me for the rude formatting but I just cannot recall how things were just that I found it awesome the ability to do the query of queries and not have all the nested selects in one statement.
e.g. SP: X
select firstName from users where active = true;
select authors from books where authorFirstName in (previous select);
Any guidance on what this style of querying is called that would help me research this would be greatly appreciated as I would like to learn more on it and follow the format more.
You can use the SQL with clause to give a sub-query a name and then use that name. Example here:
SQL WITH clause example
the form you mentioned is subquery,
which may be wrote with joins (depends on the query and subqueries):
select firstName from users where active = true;
select authors from books where authorFirstName in (previous select);
is equal to:
select books.authors
from books
join users on books.authorFirstName =users.firstName
where users.active = true;
or equal to another subquery:
select authors
from books
where exists (select firstName
from users
where
books.authorFirstName =users.firstName
and active = true);
you can also use with statement:
with cte as (
select firstName from users where active = true)
select authors from books where authorFirstName in (select firtsname from cte);
and other forms ....
This is called an subquery.
The syntax usually is as follows:
select authors from books where authorFirstName in (select firstName from users where active = true);
Similar to that are the inline view:
select authors from books join
(select firstName from users where active = true) users2 on users2.firstname = authors.authorfirstname;
and with clause
with (select firstName from users where active = true) as users2
select authors from books where authorsfirstname = users2.firstname;
All have different advantages and usages.
In my data source "Properties" is linked to "tenants" and I want to fill a table using a SQL query where tenant does not exist for that property.
In other words, "where that property is vacant."
What is the SQL statement for something like this?
SELECT tblProperties.Type, tblProperties.PropertyID, tblProperties.Street, tblProperties.Unit, tblProperties.City, tblProperties.State, tblProperties.Zip, tblProperties.Description, tblTenant.TenantID
FROM dbo.tblProperties
JOIN tblTenant
ON tblProperties.PropertyID = tblTenant.PropertyID
WHERE tblTenant.TenantID = ''
Properties and Tenants are both tables in your database?
Are they joined by a cross-reference table or...? It would be helpful to see the table structures.
Assuming that's the case, you just want something like:
SELECT * FROM Properties
WHERE PropertyId NOT IN
(SELECT PropertyId FROM PropertyTenants)
Try something like this:
SELECT Property.PropertyID, Property.TenantID
FROM Property LEFT JOIN Tenant ON Property.[TenantID] = Tenant.[TenantID]
WHERE (((Tenant.TenantID) Is Null));
This should show what properties don't have Tenants, Suggest you first try it with JUST the id fields, then add in the other fields later to keep the query simple and help with troubleshooting. If you have the potential to have multiple tenants who have offices in more than one property, this is a many-to-many relationship that is best documented in an index table.
I am using NHibernate and I my requirement is that I have 2 tables, User and Ticket. I want all the records that are in User but not in Ticket. The Ticket table has UserId as reference key to the Primary key ID of User table. Below is my code,
RegNotTickTemplate.Criteria = DetachedCriteria.For(typeof(User));
RegNotTickTemplate.Criteria.Add(Subqueries.PropertyNotIn("ID",DetachedCriteria.For(typeof(Ticket))
.SetProjection(Projections.Property("UserID"))));
The above query doesnt return correct set of records.
As an alternative, you could try using HQL. I never use Criteria as I find HQL more readable (it is almost the same as SQL except you get to query based on the entities rather than the tables).
Chapter 13. HQL: The Hibernate Query Language
IQuery query = Session.CreateQuery(
"from User where Id not in (select UserId from Ticket)");
query.List<User>();
If that is still no good, you can always do an SQL query
ISQLQuery query = Session.CreateSQLQuery(sql);
What you are missing is: the count of tickets for this user should be greater than zero. Here is how you can implement it:
RegNotTickTemplate.Criteria = DetachedCriteria.For(typeof(User));
RegNotTickTemplate.Criteria.Add(Subqueries.PropertyIn("Id",
DetachedCriteria.For<Ticket>()
.SetProjection(Projections.GroupProperty("User"))
.Add(Restrictions.Eq(Projections.RowCount(), 0))));
If you don't want the count of rows you can do the following:
RegNotTickTemplate.Criteria = DetachedCriteria.For(typeof(User),"user");
RegNotTickTemplate.Criteria.Add(Subqueries.Exists(DetachedCriteria.For<Ticket>("ticket")
.SetProjection(Projections.Property("User"))
.Add(Restrictions.EqProperty("user.Id", "User"))));