Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a database in a SQL Server 2008 database. My database model forms a diamond pattern with four tables. Those four tables are defined as follows:
Table1
- ID
- Name
- AddedBy
Table2
- ID
- Table1ID
- Name
- Type
Table3
- ID
- Table1ID
- Name
Table4
- ID
- Table2ID
- Table3ID
- Age
I am currently getting all of the Table1 records for a specific user by using the AddedBy field. This query looks like this:
SELECT
*
FROM
[Table1] t1
WHERE
t1.[AddedBy]=#someuser
Now, I need to get the Age value from the first Table4 record that is somehow associated with Table1. How do I do this? I keep getting confused with the query.
Thank you for any help you can provide!
This is a classic illustration of how compound primary keys can allow you to more accurately express what you want your database to do.
Given the model that you have, it appears that Table2 and Table3 are directly defined by Table1; that is, it doesn't make sense to have a Table2 record without a parent Table1 record. Likewise, it looks like Table4 only makes sense when both Table2 and Table3 exist. If this is true, then Table2, Table3, and Table4 should have compound primary keys along these lines:
Table2
-------------
Table1ID -- consider renaming this in Table1 so that the same name is used
throughout
RecordNumber -- unique within a given Table1ID; this is only needed if one of
your other two columns cannot serve as a unique value within
Table1ID, which I'm guessing one of them can
Then you'd do something similar for Table3. Then, for Table4, you'd have:
Table4
-------------
Table1ID
Table2RecordNumber
Table3RecordNumber
As the primary key, then set up two foreign keys, one to Table2 on (Table1ID, Table2RecordNumber) and one to Table3 on (Table1ID, Table3RecordNumber). This allows you to ensure that your Table4 records always link to Table2 and Table3 records with the same Table1ID, and it simplifies the join in the original query so that it doesn't have to go through Table2 or Table3 to find a valid record in Table4.
SQL JOIN
http://www.w3schools.com/sql/sql_join.asp
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
There are two tables in 2 different databases one table consists of Salutations example Mr, Miss and other table has names with Salutation example Mr.XYZ, Miss.ABC so I need a query which will compare the two tables and gives only those names from table 1 which are of matching salutations.
Example :
Table 1 Table 2
Salutation column Name column
Mr., Mr.Abc
Miss., Mr.XYZ
Mr. & Mrs. Mr. & Mrs. Def
Jr. xyz
So the query needs to compare two tables and give the output as
Mr.Abc,
Mr.Xyz
Mr. & Mrs. Def
I think you want join query with like:
select t2.*, t1.salutation
from table2 t2 join
table1 t1
on t2.name like concat(t1.saluation, '%');
The one caveat is that this can return more than one match. For instance, anything that matches "Mr. & Mrs." would also match "Mr.". To fix this, you can choose the longest match, using apply:
select t2.*, t1.salutation
from table2 t2 cross apply
(select top (1) t1.*
from table1 t1
where t2.name like concat(t1.saluation, '%')
order by len(t1.saluation) desc
) t1;
try this:
SELECT T2.*, T1.Salutation
FROM MyDatabase2.Myschema2.Table2 as T2
INNER JOIN MyDatabase1.Myschema1.Table1 as T1
ON T2.Name LIKE '%'+T1.Salutation+'%'
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
So I've run a SELECT which gave me this result so far:
These two columns are from different tables I've joined together. Both are stored as Numbers. In this case "ID" is the main entity and ID_1 describes a state that "ID" can be in. A main entity can have multiple states at once and multiple entities can be in the same state at the same time.
Right now, my select shows ALL entity-state-pairs on my DB. My goal for the final result is to show the rows for any entity that does not have at least one entry with their state set to 1 or 9. In the above example, I would like the final results to show the rows with the following IDs: 62 and 82
Any idea on how to archive this?
Thanks in advance!
You can use an outer join to accomplish this by doing something akin to
SELECT DISTINCT t1.ID
FROM TABLE_1 ti
LEFT OUTER JOIN (SELECT t2.ID
FROM TABLE_2 t2
WHERE t2.ID_1 IN (1, 9))
WHERE t2.ID IS NULL;
This will get the ID's from the second table where ID_1 is 1 or 9:
SELECT ID
FROM second_table
WHERE ID_1 IN (1, 9)
Using that, you can select from the first table where the ID isn't in the result set above:
SELECT DISTINCT ID
FROM first_table
WHERE ID NOT IN (
SELECT ID
FROM second_table
WHERE ID_1 IN (1, 9)
);
If you have a scenario where, for example, ID 63 has three records in the second table with ID_1 values of 3, 4 and 6, the SELECT DISTINCT will make sure ID 63 only shows once in the results instead of three times.
Addendum
Also see the answer from Bob Jarvis. The query is more involved but returns the same results. More importantly, it will run a lot faster for larger datasets.
I have two tables.
- Table 1 includes (ID, Name, gender, interestsID)
- Table 2 includes (ID, interests).
Now I want to have a new SELECT statement which show me instead of the interestsID the name behind that ID which is of course in an another table. So basically a mapping must be done and reflect the correct value behind the ID.
You need to join the two tables using I.D. The below code should work assuming your tables are actually called Table1 and Table2.
SELECT Table1.Name
FROM Table1
INNER JOIN Table2
ON Table1.ID =Table2.ID;
In order to understand joins you should refer to this link http://www.w3schools.com/sql/sql_join.asp.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
The community reviewed whether to reopen this question 9 months ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I want to left join multiple tables to one table. The tables are themselves results of subqueries.
A classical example that comes to my mind is, I have a bunch of subqueries:
1. Subquery A gives me details of students - say table 1
2. Subquery B gives me student scores in Math - say table 2
3. Subquery C gives me student scores in English - say table 3
The tables contain scores only if the student has taken that test and the student is to be considered failed if he/she has not taken test at all (or has a score < passing score). I have student IDs (unique per person) in each table to join on.
What do I want from these? I am trying to build a dynamic query (where some parts are populated at runtime by an external mechanism) by performing some joins on these tables to give me:
1. Students who passed in both tests and corresponding scores
2. Students passed in either test, but failed (or did not take) the other test and the corresponding scores (NULL if not taken).
3. All students and their corresponding scores.
What I have on mind is left joining each score table to student profile table. How should I go about this?
Before you go ahead and suggest table 1 left join table 2 left join table 3, this structure will cause problems if, say table 2 contains a null record for a particular student (as per my knowledge). And this basically joins table 3 on table 2 and not on table 1, from my understanding, which is what I want.
PS: Feel free to suggest better ways to get what I need, if you know any.
You can create the appropriate relations by writing carefully your query:
select
t1.*, t2.foo, t3.bar
from
table1 as t1
left join table2 as t2 on t1.id = t2.id
left join table3 as t3 on t1.id = t3.id
As you can see, table3 is related to table1 (not to table2), which is what you want.
I have two tables, TABLE1 and TABLE2. TABLE1 Has 4 columns: Name, Client, Position, and ID. TABLE2 has 3 columns: Amount, Time, and ID. For every ID in TABLE1 there are one or more entries in TABLE2, all with identical ID and Time values but varying Amount values.
In a view, I have a concatenated string of Name, Client, Position, and ID from TABLE1, but I also need to concatenate the Time for each ID from TABLE2 to this string. If I do a join as I create the view, I get a ton of duplicate strings in the view as it lists the same ID multiple times for each value of Amount in TABLE2.
I need to get rid of the duplicates, so I either need to avoid the replication that occurs from the join, or find a way to simply delete all the duplicates from the view.
Hopefully this is all clear enough. Thank you for reading and for any help you can provide!
DISTINCT could be appropriate:
CREATE VIEW [dbo].[View1]
AS
SELECT distinct
dbo.Table1.Id,
dbo.Table1.Name,
dbo.Table1.Client,
dbo.Table1.Position,
dbo.Table2.[Time]
FROM dbo.Table1
LEFT OUTER JOIN dbo.Table2
ON dbo.Table1.Id = dbo.Table2.Id
SqlFiddle: http://sqlfiddle.com/#!3/65651/1
On a side note, depending on what your table structures really are, you might consider having a surrogate primary key on the table2 if you don't have a natural one. I have not put one in the example, because chances are that you already have one - just making sure.