Join more than two tables with "not in" clause - c#

Can you please show me where I can INNER JOIN the tables for the FK_roomTypesID, FK_BedTypeID and FK_roomViewsID? All of the FK are on different tables from the primary.
MySqlDataAdapter da = new MySqlDataAdapter("SELECT RoomNo, RoomBedsNo,
RoomSmoking, RoomMiniBar,RoomKitchen,RoomFirePlace,RoomBalcony, RoomVeranda,
RoomGarden, RoomEntrance, RoomAirCondition, RoomTV, FK_roomTypesID,
FK_BedTypeID, FK_roomViewsID FROM tblrooms WHERE roomsID NOT IN(SELECT FK_roomsID
FROM tblbooking WHERE '" + arrdate + "' < checkOutDate AND '" + depdate + "' >
checkInDate)", conn);

You have the following part in your query:
FROM tblrooms
You define your joins in your FROM clause, therefore you should modify the code above to something like:
FROM tblrooms
join tblroomtypes
on tblrooms.FK_roomTypesID = tblroomtypes.roomTypesID
join tblbedtypes
on tblrooms.FK_bedTypesID = tblbedtypes.bedTypesID
join tblroomviews
on tblrooms.FK_roomViewsID = tblroomviews.roomViewsID
Note, that you did not give too much information, so I am guessing your table and column names here. Also, note, that I did not select any new columns. Finally, note, that you need to resolve ambiguity if the problem is applicable to your case by referring to your columns as table's columns. And format your code, it is difficult to read it. I did not use the inner keyword for the joins, because join is inner by default.

Related

I need to count students by very hard parameter, and idk how to do it

on the internet i find only very few info about count in ms access
there is query string
"SELECT students.Student FROM specialty INNER JOIN (groups INNER JOIN
((mark INNER JOIN students ON mark.idstudent = students.IDstudent)
INNER JOIN miss ON students.IDstudent = miss.IDstudent)
ON(groups.IDgroup = students.IDgroup) AND(groups.IDgroup = miss.IDgroup))
ON specialty.IDspecialty = groups.IDspecialty WHERE specialty.Name =
'" + DateFind.otdel + "' GROUP BY students.Student"
what does it - it selects all students with misses, 2, non-admission to lessons. And i need to count amount of students with that parameters.
and i tried to do something with counting via adding
SELECT COUNT(student) FROM students.student WHERE
and it does nothing. Idk how to work with count so help pls, i rly checked on internet and there was only simple queries like count by 1 field without any innerjoins and etc.
If your posted query works, then wrap this as a subquery:
"Select Count(*) From (SELECT students.Student FROM specialty INNER JOIN (groups INNER JOIN
((mark INNER JOIN students ON mark.idstudent = students.IDstudent)
INNER JOIN miss ON students.IDstudent = miss.IDstudent)
ON (groups.IDgroup = students.IDgroup) AND (groups.IDgroup = miss.IDgroup))
ON specialty.IDspecialty = groups.IDspecialty WHERE specialty.Name =
'" + DateFind.otdel + "' GROUP BY students.Student) As T"

Joining tables in SQL in one row

I have the following table structure of my database:
db structure
My aim is to output every row of tbl_Therapeuten (these are my employees) with the name of their trainings (in german "Fortbildung").
The names of the trainings are stored in tbl_Forbildungen. And the trainings which each employee has is stores in tbl_Therapeut_Fortbildung. For the output I want to show the name of the training, not the id.
Like this:
output
I am programming in C#, SQL Server.
First I tried this:
string sSQL = "SELECT t.*, STRING_AGG(tf.Id_Fortbildung, ';') AS Fortbildungen " +
"FROM tbl_Therapeuten t " +
"FULL OUTER JOIN tbl_Therapeut_Fortbildung tf on t.Id = tf.Id_Therapeut ";
But this brings an error containing that I don't use tbl_Therapeuten.Id in an aggregate function or in a Group by clause.
Next I tried this:
string sSQL = "SELECT t.Id, t.Nachname, STRING_AGG(tf.Id_Fortbildung, ';') AS Fortbildungen " +
"FROM tbl_Therapeuten t " +
"FULL OUTER JOIN tbl_Therapeut_Fortbildung tf on t.Id = tf.Id_Therapeut " +
"GROUP BY t.Id, t.Nachname";
This worked (except displaying the name of the training but the Id) but I don't want to explicitly name every column of tbl_Therapeuten. I want to use "t.*". But this is not working:
string sSQL = "SELECT t.*, STRING_AGG(tf.Id_Fortbildung, ';') AS Fortbildungen " +
"FROM tbl_Therapeuten t " +
"FULL OUTER JOIN tbl_Therapeut_Fortbildung tf on t.Id = tf.Id_Therapeut " +
"GROUP BY t.*";
So I need some help :)
And what I also don't know how to do is to display the name of the trainings instead of the id.
Thanks for your help!
You might find that a correlated subquery provides better performance (by avoiding the outer aggregation) and allows you to avoid listing all columns from t:
SELECT T.*,
(SELECT STRING_AGG(F.Name, ';')
FROM tbl_Therapeut_FortBildung TF JOIN
tbl_FortBildungen F
ON F.Id = TF.Id_FortBildung
WHERE TF.Id_Therapeut = T.Id
) as Fortbildungen
FROM Therapeuten T
I think this is what you need.
SELECT T.Id,T.Name,T.Street,T.BirthDate,STRING_AGG(F.Name,';')
FROM Therapeuten T
LEFT JOIN tbl_Therapeut_FortBildung TF ON TF.Id_Therapeut=T.Id
LEFT JOIN tbl_FortBildungen F ON F.Id=TF.Id_FortBildung
GROUP BY T.Id,T.Name,T.Street,T.BirthDate
As far as I know SQL server does not support the GROUP BY *, so you will have to specify the column names.

Duplicate rows in GridView with SQL join query

I have a GridView in my application, where I am supposed to show list of records by joining different tables. The SQL Join query shows records but say within 1000 rows it shows 2 to 3 records twice. Is it because of the sql query?
The SQL Query I am using is:
SqlDataAdapter da = new SqlDataAdapter("select dt.name, rg.sex, ad.dt_adm, st.* " +
"from stdn_st st, stdn_reg rg, stdn_det dt, admsn_det ad where st.college='" +
lbl_college.Text + "' and st.course='" + lbl_course.Text + "' and st.sem='" +
lbl_sem.Text + "' and st.pass='" + lbl_pass.Text + "' and rg.id=st.sid and " +
"dt.sid=st.sid and ad.sid=st.sid", con);
Use latest syntax of join. As per your requirement you can use any of these.
INNER JOIN
LEFT JOIN
RIGHT JOIN
OUTER JOIN

What is the difference between using a parameter and just putting a variable then convert it

So I'm retrieving data from the database using odbc. One of my fields, which was causing the problem, is AutoNumber. In my query when I use, '" convert.toint64(empid)"', I get an error of data type missmatch. But when I used parameter, it worked perfectly. Can someone tell me what is the difference. As far as I know, AutoNumber is a long integer and long int is 64, right?
here are both of my queries:
string cmdText = "SELECT p.projID, p.projName, a.wageperday " +
"FROM ((projects p INNER JOIN assigns a ON p.projID = a.projname) " +
"INNER JOIN empos e ON a.employeeID= e.ID) " +
"WHERE a.employeeID = ?";
OdbcCommand assignslist = new OdbcCommand(cmdText, _connection);
assignslist.Parameters.AddWithValue("#empID", empid);
OdbcDataReader readassigns = assignslist.ExecuteReader();
GridView1.DataSource = readassigns;
GridView1.DataBind();
(this one works fine)
string cmdText = "SELECT p.projID, p.projName, a.wageperday " +
"FROM ((projects p INNER JOIN assigns a ON p.projID = a.projname) " +
"INNER JOIN empos e ON a.employeeID= e.ID) " +
"WHERE a.employeeID = '" + convert.toint64( empid ) + "';
OdbcCommand assignslist = new OdbcCommand(cmdText, _connection);
OdbcDataReader readassigns = assignslist.ExecuteReader();
GridView1.DataSource = readassigns;
GridView1.DataBind();
for this one, i get an error even if I removed the conversion, I get an error.
One more question, I don't understand INNER JOIN perfectly and the above code was from a user here who helped me. I don't understand why did he use "FROM ((projects p INNER JOIN assigns a ON p.projID = a.projname) " +
"INNER JOIN empos e ON a.employeeID= e.ID)"
two brackets -- I mean a bracket inside a bracket. And if I wanna join a 4th or 5th table do I have to put it inside a bracket aside from the main bracket? An example would be much appreciated!
If a.employeeID is a number then your problem are the quotes and the concatenation of a number to a string.
"WHERE a.employeeID = " + convert.toint64(empid).ToString()
but this make no sense because you have a string to build so, you could simply write
"WHERE a.employeeID = " + empid.ToString();
however use always the parameterized query. That is the correct way to go.
A parameterized query allows the Framework code to pass the parameters with the correct format and you don't have to worry about quoting values, format of dates and decimal separators. (And last but not least, you avoid any possibilities of Sql Injection)
For the second part of your question, JOIN is used to put togheter data from two tables, when you have more than one JOIN the parenthesys help to understand how the grouping from the tables are perfomed. First the data from projects and assigns are grouped together following the rules of the INNER JOIN then the resulting set of data is joined with the data from the employee table following the rules of the second join.
In your second query, instead of using convert.toint64( empid ) try using empid.ToString():
"WHERE a.employeeID = " + empid.ToString();
The error you were receiving was due to the fact that you were trying to concatenate a string with an integer.
With regards to the INNER JOINs you are using, the use of the brackets is dependant upon the database you are using. In most cases, you will not need the brackets at all and they can be removed without any issue, so you could rewrite the query to:
string cmdText = "SELECT p.projID, p.projName, a.wageperday " +
"FROM projects p " +
"INNER JOIN assigns a ON p.projID = a.projname " +
"INNER JOIN empos e ON a.employeeID = e.ID " +
"WHERE a.employeeID = " empid.ToString();
You're trying to add a string and an integer, which isn't allowed automatically. You'd have to convert the number to a string first, like this:
"WHERE a.employeeID = '" + empid.ToString() + "';
But, using parameters is the better way for other reasons (best habit to be in, to avoid SQL-injection attacks, etc.).

Trying to Query 2 Access tables with 1 statement

I've been doing research and cannot find a way to get data from multiple tables using one query. What I want to achieve is getting information from one table in an Access database and using that information to get more data from a different table in the same database
Here's the code I have so far...
string end = "ENDDATE";
string qual = "CGA0113";
string start = "START";
ad.SelectCommand = new OleDbCommand("SELECT* FROM [AC_ECONOMIC] Where KEYWORD = '" + end + "'AND QUALIFIER = '" + qual + "' AND EXPRESSION LIKE 'SN%'", con);
I want to be able to get data from a separate table called AC_PROPERTY with the same SN from the query above from that AC_ECONOMIC table. I was researching joins and believe that is the way to go but I'm not quite sure of the syntax or if that would even work. Any help would be greatly appreciated.
Correct, an inner join would be the way to go. You basically need to construct a statement that joins the 2 tables by their common field. Something like this:
SELECT * FROM [AC_ECONOMIC] a
INNER JOIN [AC_PROPERTY] b
on [AC_ECONOMIC].SN=[AC_PROPERTY].SN
Where KEYWORD = '" + end + "'AND QUALIFIER = '" + qual + "' AND EXPRESSION LIKE 'SN%'
Above statement is just an example. I don't know if the common column between the 2 tables is actually called "SN".
UPDATE:
As suggested by #Geek, you can also alias the tables after you reference them in your statement, this saves you from typing the full table names every time. For example, the above statement can also be written as:
SELECT a.*, b.* FROM [AC_ECONOMIC] a
INNER JOIN [AC_PROPERTY] b
on a.SN=b.SN
Where a.KEYWORD = '" + end + "'AND a.QUALIFIER = '" + qual + "' AND b.EXPRESSION LIKE 'SN%'
Note how the WHERE clause is filtering using columns from both, "a" (AC_ECONOMIC) and b (AC_PROPERTY).

Categories