How to query twice at once from one table with inner join SQL ASP.NET - sql

I have two tables first table called TFile contains two columns: FromCity and ToCity.
They will have different values but from one column of the second table (TCity) and specifically from the column called CityName.Second table name TCity they have two column : IdCity AND CityName.
My problem I need to display data for two columns they got from second table FromCity and ToCity with inner join for two times.
I use this code to do that:
SqlCommand comm = new SqlCommand("select * from TFile " +
"inner join TCity AS A ON TFile.FromCity = A.IdCity " +
"inner join TCity AS B ON TFile.ToCity = B.IdCity " + " WHERE " + "TFile.Name", con);
Then display data to users as:
SqlDataReader srd = comm.ExecuteReader();
if (srd.HasRows)
{
while (srd.Read())
{
//FromCity
TextFrom.Text = srd["CityName"].ToString();
//ToCity
TextTo.Text = srd["CityName"].ToString();//=======================here problem
}
}
In the first line of the data display I can get the name of the city but if I repeat that in the second line it will just repeat the data. Here problem.I can't use a different name to access the second query instead of the field name CityName.This is the name of the field in the second table for which I display the names of the cities.
How can I access to data in this query:
"inner join TCity AS B ON TFile.ToCity = B.IdCity
So if I access to it then can display second data in this line:
TextTo.Text = srd["CityName"].ToString();
How can solve this problem ?

I bet you need to create field aliases to differentiate between values from the multiple joins on the same table. By the way, please make sure you protect yourself from "SQL injection" when using these types of queries. If you don't know what "SQL Injection" is then please take some time to look it up.
"select FromCityName=A.CityName, ToCityName=B.CityName, * from TFile "
And
//FromCity
TextFrom.Text = srd["FromCityName"].ToString();
//ToCity
TextTo.Text = srd["ToCityName"].ToString();//=======================here problem

Related

Dynamic Selection Query with Criteria in Ms Access | SQL

I have a query in which I select multiple values. To create my form.
The results look like this :
the last Column [Candidat Nom] is a drop down list with an other query (lets call it Query 1) that select my drop down list values.
The selection is good and is what I'm looking for. Except I get the same value for all lines when they need to be different.
To simplify
let's take the following exemple
I have the following candidate that wants to join for the following job (Represented with their ID).
As we can see 2 candidates wants job N° 12. and 1 candidate for each other job.
What I get
All candidates are listed for every job.
What I want
What I actually did
is I put the following query (Query 1) on my column.
SELECT T_SALARIE.SALARIE_nom & " " & T_SALARIE.SALARIE_prenom AS Candidat Nom
FROM T_EMPLOI INNER JOIN (T_SALARIE INNER JOIN (T_SALARIE_EMPLOI LEFT JOIN T_STATUT_EMPLOI ON T_SALARIE_EMPLOI.SALARIE_EMPLOI_statut_id = T_STATUT_EMPLOI.STATUT_EMPLOI_id) ON T_SALARIE.SALARIE_NNI = T_SALARIE_EMPLOI.SALARIE_EMPLOI_salarie_nni) ON T_EMPLOI.EMPLOI_identifiant = T_SALARIE_EMPLOI.SALARIE_EMPLOI_emploi_identifiant
WHERE (((T_STATUT_EMPLOI.STATUT_EMPLOI_statut) Like "*valid*" Or (T_STATUT_EMPLOI.STATUT_EMPLOI_statut) Like "*décidé*") AND ((T_EMPLOI.EMPLOI_entreprise_id)=1));
This gave me the result I want but with the issue I mentioned previously (Same result for each line)
So
I thought I needed a new Criteria.
I added one, where It's going to select the candidate when the two "emploi ID" of my actual table (Shown before) and the one helping me select the candidates are equal.
With the following query:
SELECT T_SALARIE.SALARIE_nom & " " & T_SALARIE.SALARIE_prenom AS Candidat, T_SALARIE_EMPLOI.SALARIE_EMPLOI_emploi_identifiant
FROM T_EMPLOI INNER JOIN (T_SALARIE INNER JOIN (T_SALARIE_EMPLOI LEFT JOIN T_STATUT_EMPLOI ON T_SALARIE_EMPLOI.SALARIE_EMPLOI_statut_id = T_STATUT_EMPLOI.STATUT_EMPLOI_id) ON T_SALARIE.SALARIE_NNI = T_SALARIE_EMPLOI.SALARIE_EMPLOI_salarie_nni) ON T_EMPLOI.EMPLOI_identifiant = T_SALARIE_EMPLOI.SALARIE_EMPLOI_emploi_identifiant
WHERE (((T_STATUT_EMPLOI.STATUT_EMPLOI_statut) Like "*valid*" Or (T_STATUT_EMPLOI.STATUT_EMPLOI_statut) Like "*décidé*") AND ((T_SALARIE_EMPLOI.SALARIE_EMPLOI_emploi_identifiant)=[R_Select_COMOB]![ACTION_identifiant_emploi]));
But I keep on getting the following pop up that asks me to enter a Job ID
So how can I make the query for each line compare and select the right values?
I hope I was clear in explaining. If not please let me know so that I can add more details.
Thank you !
Thanks to your help and specially #June7 for his propositions, I found a solution regarding my problem :
I added a criteria to select values based on JobID that I wasn't selecting in the first hand.
And then based on the column (jobID) select the values needed
here is my final query :
SELECT
[SALARIE_nom] & " " & [SALARIE_prenom] & " (" & [SALARIE_NNI] & ")" AS Salarié, T_SALARIE_EMPLOI.SALARIE_EMPLOI_salarie_nni, T_SALARIE_EMPLOI.SALARIE_EMPLOI_id, T_SALARIE_EMPLOI.SALARIE_EMPLOI_emploi_identifiant
FROM
(T_STATUT_EMPLOI INNER JOIN T_SALARIE_EMPLOI ON T_STATUT_EMPLOI.STATUT_EMPLOI_id = T_SALARIE_EMPLOI.SALARIE_EMPLOI_statut_id) LEFT JOIN R_Select_Salarie ON T_SALARIE_EMPLOI.SALARIE_EMPLOI_salarie_nni = R_Select_Salarie.SALARIE_NNI
WHERE
(((T_SALARIE_EMPLOI.SALARIE_EMPLOI_emploi_identifiant)=[Formulaires]![F_COMOB]![ACTION_identifiant_emploi]) AND ((T_STATUT_EMPLOI.STATUT_EMPLOI_statut) Like "*validé*") AND ((T_SALARIE_EMPLOI.SALARIE_EMPLOI_Entreprise) Like "*RTE*"));
And Then to update my values for each line. I added a VBA code that requery on input.
Private Sub ACTION_Candidats_P_Enter()
ACTION_Candidats_P.Requery
End Sub
With that my problem is solved.

What would be the SQL query for my problem?

I need help with a SQL query for room within an android app. There is a table questions. This table has 3 columns:
id question id_sub_cateory
Furthermore there is table_sub_categories with folloing columns:
id sub_category id_category
And table_categories:
id category id_subject
Additionally there is a table_subject:
id subject id_questionnaire
Last but not least table_questionnaire:
id questionnaire
Now I would like to have a SQL query to get following information:
table_questionnaire.id table_questionnaire.questionnaire questionCount subjectCount
So basically a list which lists all questionnaires with number of questions and subjects included. What would be the SQL query for that?
EDIT: So far I have used this query:
SELECT table_questionnaire.id AS 'id', table_questionnaire.questionnaire_name AS 'name', " +
"COUNT(table_question.id_questionnaire) AS 'questionCount', COUNT(DISTINCT table_question.subject) AS 'subjectCount' " +
"FROM table_questionnaire " +
"LEFT JOIN table_question ON table_questionnaire.id = table_question.id_questionnaire GROUP BY table_questionnaire.id"
But this one is an old version because I saved each question with an ID of questionnaire, subject, category and sub_category. I recognized that this information is redundant. Now I save only the ID of sub_category. But now I have to change the query. I just don't know how!?
This is the query which works:
SELECT
table_categories.id,
table_categories.id_subject,
table_categories.category,
table_sub_categories.id AS 'id_sub_category',
table_sub_categories.id_category,
table_sub_categories.subCategory,
COUNT(id_category) AS 'questionsCount'
FROM table_question
LEFT JOIN table_sub_categories ON table_question.id_sub_category = table_sub_categories.id
LEFT JOIN table_categories ON table_categories.id = id_category
WHERE table_categories.id_subject = :subjectID
GROUP BY table_categories.id

How Query.getResultList() works

So I have the follow code.
Query query = getEntityManager()
.createQuery(
"SELECT m.memCategory, m.copClass, SUM(b.paidAmt) paidAmt FROM BuildingFundModel b "
+ "INNER JOIN b.memberModel m WHERE b.memberModel != NULL AND b.paidDt BETWEEN :dtFrom AND :dtTo "
+ "GROUP BY m.memCategory, m.copClass");
query.setParameter("dtFrom", dtFrom);
query.setParameter("dtTo", dtTo);
lstObj = query.getResultList();
However, when I run this, it always returns only two columns. Is that How Query.getResultList() should work?
This query will return a list containing one or more Object[]. The number of items in the list correlates to the number of rows returned, while each Object[] should contain 3 items, one for each column.
The Query.getResultList() method replaces the place holders in the query with the variables from the query.setParameter. It then executes the query returning what is selected in the SELECT statement.
Try this query:
Query query = getEntityManager().createQuery(
"SELECT m.memCategory, m.copClass, SUM(b.paidAmt)
FROM BuildingFundModel b
INNER JOIN b.memberModel m
WHERE b.memberModel IS NOT NULL AND b.paidDt BETWEEN :dtFrom AND :dtto
GROUP BY m.memCategory,m.copClass");
query.setParameter("dtFrom", dtFrom);
query.setParameter("dtTo", dtTo);
lstObj = query.getResultList();

Querying multiple tables and displaying the outcome wtih SQL and Access

I need to display the customers that have purchased a product (based on a user search) in a list box. I have five different tables in Access which store different information and that relate to each other with IDs (using combox boxes in vb). I need to be able to search for a product, for example "White Bread", the program then should display the customer's full name and address as stored in the database.
Table: TransactionDetails
Fields: ID, stockID, custTransID
Table: CustomerTransaction
Fields: ID, custID, dateOfTransaction
Table: CustomerAccountDetails
Fields: ID, custFullName, custAddress, custLandline,
custMobile, custDOB, custCreditDetails
Table: StockDescription
Fields: ID, stockName, stockDesc, stockPrice
Table: SupplierDetails
Fields: ID, supplierName, supplier Address
I think I need to use INNER JOIN to query multiple tables at once but I am unsure of the syntax (I'm new to SQL). So far I have this:
Dim productSearch As String
productSearch = productSrchInput.Text
Dim databaseConnection As New OleDb.OleDbConnection
Dim counter As Integer
Dim array(10) As String
databaseConnection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=assignment5database.accdb"
databaseConnection.Open()
Dim searchDatabase As OleDbCommand = New OleDbCommand("SELECT CustomerAccountDetails.custFullName, CustomerAccountDetails.custAddress " & _
"FROM CustomerAccountDetails " & _
"INNER JOIN StockDescription ON TransactionDetails.stockID = TransactionDetails.custTransID " & _
"WHERE StockDescription.stockName = '" & productSearch & "'", databaseConnection)
Dim searchResults As OleDbDataReader = searchDatabase.ExecuteReader
counter = 1
Do While searchResults.Read
srchResultsList.Items.Add(searchResults.Item(0))
counter += 1
Loop
databaseConnection.Close()
You are missing some of the joins that connect the customer to the stock details. Here is the SQL that Access will expect in order to pull the data based on your description. The parentheses may seem extraneous, if you are used to SQL server or MySQL, but Access will throw a fit if you leave them out.
SELECT CustomerAccountDetails.custFullName, CustomerAccountDetails.custAddress, StockDescription.stockName
FROM StockDescription
INNER JOIN ((CustomerAccountDetails
INNER JOIN CustomerTransaction ON CustomerAccountDetails.ID = CustomerTransaction.custID)
INNER JOIN TransactionDetails ON CustomerTransaction.ID = TransactionDetails.custTransID) ON StockDescription.ID = TransactionDetails.StockID
WHERE StockDescription.stockName="something"
As noted by Fionnuala, I will almost always build a query that has multiple joins in it using the Access query designer before putting it in code. I almost always leave out a set of parentheses or try to write the query in a structure that SQL Server would expect and get rejected by Access.
I think you could be able to use an inner join but perhaps a "union" may be more efficient.
http://www.w3schools.com/sql/sql_union.asp is good for improving sql knowledge, it helped me a lot.

SQL Join Query VB (Pretty Sumple, I'm just learning)

I'm trying to make a query which has the same field in table A & table B. Then table B has the same field as table C. I want to left join all tables on table A. Is this possible? If yes, how close is my code to doing it?
Try
objConn = DBAccess.GetConnection
strBlder.Append("SELECT ")
strBlder.Append("FLD_NM, DATA_TYPE_CD, XML_PATH_TX, UPDT_USER_ID_NR, DOC_TMPL_FLD_ID_NR ")
strBlder.Append("FROM ")
strBlder.Append("LLC.[LLCW10_DCTMPFLD_TB] LEFT JOIN LLC.[DataMapTool_FieldMapping] ")
strBlder.Append("ON LLC.[LLCW10_DCTMPFLD_TB].DOC_TMPL_FLD_ID_NR = LLC.[DataMapTool_FieldMapping].DocumentTemplateFieldID ")
strBlder.Append("& LEFT JOIN LLC.[DataMapTool_FieldMapping] ")
strBlder.Append("ON LLC.[DataMapTool_FieldMapping].FieldMappingStatusID = LLC.[DataMapTool_FieldMappingStatus].FieldMappingStatusID ")
strBlder.Append("ORDER BY FLD_NM ;")
dsData = DBAccess.ExecuteDataTable(objConn, CommandType.Text, strBlder.ToString())
'execute non query - takes sp name
The error you are getting(after removing the &) is because LLC.[DataMapTool_FieldMapping] is repeated and thats a problem. Instead of your from clause try something like:
FROM (LLC.[LLCW10_DCTMPFLD_TB] LEFT JOIN LLC.[DataMapTool_FieldMapping] ON LLC.[LLCW10_DCTMPFLD_TB].DOC_TMPL_FLD_ID_NR = LLC.[DataMapTool_FieldMapping].DocumentTemplateFieldID)
LEFT JOIN LLC.[DataMapTool_FieldMappingStatus] ON LLC.[DataMapTool_FieldMappingStatus].FieldMappingStatusID = LLC.[DataMapTool_FieldMapping].FieldMappingStatusID
Note that the LLC.[DataMapTool_FieldMapping] is referenced in the first join and then only the .FieldMappingStatusID field is referenced in the second join. Your initial query would have been trying to add the same table to the query twice without giving it an alias which confuses the query analyzer.
Basically the new from clause will attach the first two tables together then attach the third table onto the result of the first join.
Looks good to me, but there is that strange & before the LEFT JOIN LLC.[DataMapTool_FieldMapping] ... take that out.