Selecting all rows whos foreign key points to a specific primary key?
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 20开发者_StackOverflow中文版08, 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.
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'
Are you just looking for a simple filter? SELECT * FROM tasks WHERE userid=0
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
精彩评论