I am new to sql so please bear with me here. I have two tables, COURSES and RESPONSES which have a common field userID. I am making a grid view which displays each users available courseName from the COURSES table and dateTaken from the RESPONSE table. So I simply wrote the query as:
SELECT c.*, r.*
FROM COURSES c, RESPONSE r
WHERE c.userID = @userID1 and r.userID = @userID1 and r.userResponse = NULL
<SelectParameters>
<asp:Parameter Name="userID1" Type="Int32" />
</SelectParameters>
<asp:GridView
ID ="gvAvailCourses"
runat ="server"
DataSourceID ="sdsAvailCourses"
Width ="100%"
DataKeyNames ="trainingCourseID"
PageSize ="10"
AllowPaging ="true"
EnablePersistedSelection="true"
OnRowCommand ="gvAvailCourses_RowCommand"
AutoGenerateColumns ="false">
<Columns>
<asp:BoundField DataField="trainingCourseID" HeaderText="Coursen ID" />
<asp:ButtonField ButtonType="Link" DataTextField="CourseName" CommandName="CourseName" HeaderText="Course Name" />
<asp:BoundField DataField="dateEntered" HeaderText="Last Taken" />
The RESPONSE table may or may not have a record of a users response, so there may be no record for a particul开发者_运维知识库ar userID.
In any case, I have to display in my grid view, any couseName that is in the COURSES table regardless of its value in the RESPONSE table. If the RESPONSE table does not have a record for that user, then the grid view will just display blank there or say "Not Taken Yet" for the dateTaken column. My above query does not display anything at all if there is no record in the RESPONSE table. Please help.
Thanks!
What you're looking for is a LEFT OUTER JOIN. This allows the second table to be included in the query if there is information present, otherwise the referenced columns will return NULL values.
SELECT c.*, r.*
FROM COURSES c
LEFT JOIN RESPONSE r
ON r.userID = c.userID
WHERE r.userResponse = NULL
Check out inner joins and left/right modifiers thereof.
What you are describing is a left join from courses to response. Give all courses, show the associated response if its there, otherwise null
SELECT c.*, r.*
FROM COURSES c LEFT JOIN RESPONSE r
ON c.userID = r.userID
精彩评论