How to use JOIN on database. - c#

(SQLite and C#)
I have this little problem. See those 2 tables. 1. is parent, 2. is child
I should get "broj_goluba" from parent table to match "par_m" and "par_z" in child table and later just display it in datagridview.
Foregin keys should help to get things done fast, but here when I write code I have much more lines of code opposed to not using foreign keys.
Could someone please help me and write down how my code (EDIT: SQL query) should look like when using foreign keys.

What I understand you need is that, but it doesn't have to do anything with speed. Maybe you mean INDEX and not FOREIGN KEY.
SELECT BROJ_GOLUBA
FROM TABLE1
INNER JOIN TABLE2 ON (TABLE1.ID = TABLE2.PAR_M OR TABLE1.ID = TABLE2.PAR_J)
Or maybe you need BOTH values to be equal:
SELECT BROJ_GOLUBA
FROM TABLE1
INNER JOIN TABLE2 ON (TABLE1.ID = TABLE2.PAR_M AND TABLE1.ID = TABLE2.PAR_J)

Foreign keys don't exist to "help to get things done fast". They exist to enforce data integrity. Frankly, I don't see how the number of lines of T-SQL code you write is dependent on whether or not foreign keys exist.
The following query stub should help get you started on your query:
Select Table1.broj_goluba, Table2.par_z ...
From Table1
Inner Join Table2 on Table1.ID = Table2.par_m

Related

Get foreign key field from primary key in another table that linked to many table

My database is designed in SQL Server & I want get output in asp.net, LINQ, C#
I have 2 tables linked to 1 table (1:1)
My question is can I get a primary key linked to which table?
For example:
tbl_Document (ID, Date, ...)
tbl_Factor (ID, DocID, ...)
tbl_Finance (ID, DocID, ...)
What is the best way to know ID in tbl_Document linked to which table?
I can add record in tbl_Document as 'whichTable' and write the name of table in every column, and every time I want to search set "if" and check 'WhichTable'.
Is there a better way to do that?
Thanks, and sorry for my bad English :)
By default, you can get only all tables that have foreign key constraints to the parent table:
select object_name(f.referenced_object_id) pk_table, c1.name pk_column_name,
object_name(f.parent_object_id) fk_table, c2.name fk_column_name
from
sys.foreign_keys f
join sys.columns c1 on c1.object_id = f.referenced_object_id
join sys.columns c2 on c2.object_id = f.parent_object_id
join sys.foreign_key_columns k
on (k.constraint_object_id = f.object_id
and c2.column_id = k.parent_column_id
and c1.column_id = k.referenced_column_id )
where object_name(f.referenced_object_id) ='tbl_Document'
There is no such additional information regarding every particular row in parent table. It would be a duplicate information (since you can figure out it by searching in every child table). Thus, as you mentioned you can store child table name in the additional column and then as an option, construct sql dynamically to query child row.

MSSQL Query Not Returning Null Columns/Results

I'm kind of new to SQL queries so this is probably something easily fixed, but I can't seem to find any answers.
I've got a bunch of related tables. E.g.
SPClients contains iClientID and sName, SPDocTypes contains iDocTypeID and sName, SPCreditor contains iCreditorID and sName
and then
SPDocIndex contains iIndexID, and then foreign keys to iClientID, iDocTypeID and iCreditorID listed above.
If I do a simple SELECT * FROM SPDocIndex I get all results, with just the IDs being displayed, which isn't much use when bound to a datagrid. So I use an inner join so the actual names appear rather than just their IDs, like so:
SELECT * FROM SPDocIndex
INNER JOIN SPClients ON SPDocIndex.iClientID=SPClients.iClientID
INNER JOIN SPDocType ON SPDocIndex.iDocTypeID=SPDocType.iDocTypeID
INNER JOIN SPCreditor ON SPDocIndex.iCreditorID=SPCreditor.iCreditorID
And the query "works" but it only returns rows that have data in all three columns. If the iCreditorID column of SPDocIndex is null, then that row is NOT returned...but I would like all rows to be returned irrespective of whether the columns are null or not.
Benny - some of the others responded in the comments, that you'll need to adjust your join to a left join instead of an inner join; indeed, that is the case here. Please check out this link for a quick tutorial on the differences between SQL joins.
https://www.w3schools.com/sql/sql_join.asp
Inner Join will always return the return the matching records within two table. In order to get the all the records from first table and matching record of second table you must use left join as shown below. Please try below and let me know if you have any further issues.
SELECT * FROM SPDocIndex
LEFT JOIN SPClients ON SPDocIndex.iClientID=SPClients.iClientID
LEFT JOIN SPDocType ON SPDocIndex.iDocTypeID=SPDocType.iDocTypeID
LEFT JOIN SPCreditor ON SPDocIndex.iCreditorID=SPCreditor.iCreditorID

Construct a dynamic query (or algorithm) based on existing query

I have a task to construct a dynamic query (or algorithm) based on existing query with user choosed fields. Let me explain:
Lets say I have a function
ConstructQuery(string inputQuery, string[] mandatoryTables, string[] userFields) with 2 input parameters:
inputQuery: string query with many fields and tables, joins and where conditions
mandatoryTables: a list of mandatory tables
userFields: a list of fields that user choose in some web or desktop app
Function would have to return optimized query with tables and joins that are only needed for query to succeed.
inputQuery is for example constructed like this:
SELECT
Table1.SomeFieldA,
Table2.SomeFieldB,
Table2.SomeFieldC,
Table3.SomeFieldD
FROM Table1
JOIN Table2 ON Table1.Code = Table2.Code
JOIN Table3 ON Table2.Code = Table3.Code
WHERE Table1.SomeConditionField = "xyz"
userFields are: SomeFieldB, SomeFieldC
mandatoryTables: Table1
So the expected query is:
SELECT
Table2.SomeFieldB,
Table2.SomeFieldC
FROM Table1
JOIN Table2 ON Table1.Code = Table2.Code
WHERE Table1.SomeConditionField = "xyz"
My question is: is there a tool of some sort for solving this kind of problems or how you guys would solve it? I'm thinking of binary trees…
Regards,
Jani
This is something called join removal. This is (very) hard. Just parsing the query is nontrivial, then You'd have to analyze semantics, consider what are the unique keys, what are foreeign keys to have a chance to remove some tables. In Your example: the algorithm would have to know that table3.code is unique, and a foreign key to table2.code, otherwise the queries are not equivalent.
It could be easier to generate the right query in the first place. This is what some ORMs do.

Getting Value From Another Table with a Foreign Key

I've built a report with the report wizard in C#, and I can see my report in ReportViewer. My problem is that I have 2 tables that are related. The value of a column in the first table is a foreign key on the other table. All I see in that column is just the foreign key. I'd like to see the corresponding value from the other table.
How can I see value of the column from the second table?
You should just join on the foreign key columns:
SELECT
a.*,b.YourNeededColumnHere
FROM TableA a
INNER JOIN TableB b ON a.columnX=b.columnX
However, if you are having problems doing this in reporting services, just create a view:
CREATE VIEW CombinedAB
AS
SELECT
a.*,b.YourNeededColumnHere
FROM TableA a
INNER JOIN TableB b ON a.columnX=b.columnX
GO
you should now be able to run your report off the CombinedAB view as:
SELECT
*
FROM CombinedAB
WHERE ...your conditions here...
sounds like you probably need a drill down report
Create Basic Drilldown Report
Regarding the control that renders the result... Does it have its columns bound manually / is it set to auto-bind?
Change your query to one that involves the fields from the appropriate tables.
SELECT t1.*, t2.value
FROM table1 t1
JOIN table2 t2 ON t1.t2id = t2.id
But if you can't, because the data sources are separate, then you'll be wanting another option.
Assuming you have two datasets, from separate data sources.
Put a table in your report to show information from DataSet1 (or whatever it's called). Then put a rectangle in place of one of your textboxes, and then put a table in there, which you attach to DataSet2. Then put a filter on this table, so that it only shows records from DataSet2 which correspond to the appropriate value in DataSet1.
Or, wait for SQL Server 2008 R2 (currently in CTP), which provides a Lookup function for exactly this purpose.
Rob
Drag the item from the table where it's the Foreign Key, not it's native location.

How to programmatically find a many to many relation in an SQL Server 2005 database

I can find a direct table foreign key in c# like:
foreach (ForeignKey key in CurrentTable.ForeignKeys) {
Console.WriteLine("FK:" + key.ReferencedTable);
}
The classic representation for a many to many relationship is achieved via an intermediate table that has a one to many relation to the two principal tables so there is not a direct link between the tables that have the many2many relation.
For the moment I try to find the many to many relation checking if the table I am analyzing has only two columns and both colums are foreign keys to different tables (in that case I recognise this as the intermediate table).
This is not the best solution as sometimes the intermediate table carries also other columns.
What would the best way to find this many2many relation programmatically?
As additional criteria you could use the fact that in many cases the couple of the two foreign keys represents the primary key of the join/intermediate table.
You seem to have posited your own solution. Rather than searching for tables that have two foreign keys referencing other distinct tables and with no other columns, just delete the phrase "and with no other columns".
In other words, look for "tables that have two foreign keys referencing other distinct tables".
This statement finds all tables with at least two foreign key columns
SELECT objects_1.name AS Master1, objects_2.name AS Master2, sys.objects.name AS Detail,
sys.columns.name AS Column1, columns_1.name AS Column2
FROM sys.objects
INNER JOIN sys.columns ON sys.objects.object_id = sys.columns.object_id
INNER JOIN sys.foreign_key_columns ON sys.columns.column_id = sys.foreign_key_columns.parent_column_id
AND sys.columns.object_id = sys.foreign_key_columns.parent_object_id
INNER JOIN sys.objects AS objects_1 ON sys.foreign_key_columns.referenced_object_id = objects_1.object_id
INNER JOIN sys.columns AS columns_1 ON sys.objects.object_id = columns_1.object_id
AND columns_1.column_id <> sys.columns.column_id
INNER JOIN sys.foreign_key_columns AS foreign_key_columns_1 ON columns_1.object_id = foreign_key_columns_1.parent_object_id
AND columns_1.column_id = foreign_key_columns_1.parent_column_id
INNER JOIN sys.objects AS objects_2 ON objects_2.object_id = foreign_key_columns_1.referenced_object_id
WHERE (sys.columns.is_nullable = 0) AND (columns_1.is_nullable = 0)
ORDER BY Master1, Detail, Master2
If a table has foreign key columns to two different tables, then it definitely represents the many to many relationship between the tables. The fact that the table has other columns only means that the relationship between the tables(entities) is further qualified by the extra attributes. Have a look at the example in the figure below:
In the example above there is a many to many relationship between product and bill. The intersection table will also have descriptive attributes like 'quantity', 'gift wrap' etc.. That does not take away the fact that there is a many to many relationship in the first place. The tables would look like this
Product(prod_id, name, unitweight, uom)
Bill(BillNo, date, amount,uom)
BillItems(prod_Id, BillNo,quantity,gift_flg)

Categories