views:

40

answers:

3

I have two tables. One is a 'Users' table. Each row (user) in the table has a unique id (primary key).

The second table is a 'Tasks' table. Each row in the Tasks table has a foreign key which points to the user (in the Users table) that owns that task.

Using SQL Express 2008, what query must I use to obtain a list of all tasks assigned to a user? For example, if I have a user in the Users table with a primary key of 0 and there are 10 rows in the Tasks table with a foreign key value of 0, that means that this user has 10 tasks assigned to him. I need to build a query that gives me these 10 rows from the Tasks table.

+2  A: 

Are you just looking for a simple filter? SELECT * FROM tasks WHERE userid=0

JamesMLV
+1  A: 

I think you can achieve what you want with a simple single table select, assuming you know the id of the user:

SELECT *
FROM Tasks
WHERE user_id = 1234
Mark Byers
+4  A: 

If you have the user PK

select tasks.*
from tasks 
where tasks.UserId = 0

if you have the user name

select tasks.*
from tasks 
inner join users on users.UserId = tasks.UserId
where users.UserName =  'Bob'
Scott Weinstein
What is the tasks. syntax you're using? For your first snippet, why are you doing "tasks.*" instead of just "*"?
Bob
@Bob - I wrote the second example first
Scott Weinstein
@scott I'm asking because I don't understand the syntax. I'm very new to SQL. Is it the same as how namespaces work in C#?
Bob
More like an instance of a class.
Scott Weinstein
@Bob: `tasks.*` just selects all columns from the `tasks` table. This is particularly useful in the second query, since you probably don't want all columns from all tables involved in the JOIN operation.....
marc_s