Select from one table where not in another in SQL Server

goucqfw6  于 2023-03-22  发布在  SQL Server
关注(0)|答案(2)|浏览(147)

I have a SQL Server database on my computer, and there are two tables in it.

This is the first one:

SELECT  
    [ParticipantID]
    ,[ParticipantName]
    ,[ParticipantNumber]
    ,[PhoneNumber]
    ,[Mobile]
    ,[Email]
    ,[Address]
    ,[Notes]
    ,[IsDeleted]
    ,[Gender]
    ,[DOB]
FROM 
    [Gym].[dbo].[Participant]

and this is the second one

SELECT  
    [ParticipationID]
    ,[ParticipationNumber]
    ,[ParticpationTypeID]
    ,[AddedByEmployeeID]
    ,[AddDate]
    ,[ParticipantID]
    ,[TrainerID]
    ,[ParticipationDate]
    ,[EndDate]
    ,[Fees]
    ,[PaidFees]
    ,[RemainingFees]
    ,[IsPeriodParticipation]
    ,[NoOfVisits]
    ,[Notes]
    ,[IsDeleted]
FROM 
    [Gym].[dbo].[Participation]

Now I need to write a T-SQL query that can return

SELECT 
    Participant.ParticipantNumber,
    Participation.ParticipationDate,
    Participation.EndDate
FROM
    Participation
WHERE 
    Participant.ParticipantID = Participation.ParticipantID;

and I'm going to be thankful

jtw3ybtb

jtw3ybtb1#

---- select * from table 1 where ids not exist in table 2 ----

idsTable2 = array(); I create a select from table 2 bring me the ids foreach $x = key[ids]; idsTable2[] = $x; //2,6,10,15 end foreach $idsTable2 = implode($idsTable2, ','); // now its a string

select * from table1 NOT IN ($idsTable2)

it's like doing

select * from table1 NOT IN (2,6,10,15)

wr98u20j

wr98u20j2#

SQL Server performs sort, intersect, union, and difference operations using in-memory sorting and hash join technology. Using this type of query plan, SQL Server supports vertical table partitioning, sometimes called columnar storage.

SQL Server employs three types of join operations:

Nested Loops joins Merge joins Hash joins Join Fundamentals By using joins, you can retrieve data from two or more tables based on logical relationships between the tables. Joins indicate how Microsoft SQL Server should use data from one table to select the rows in another table.

A join condition defines the way two tables are related in a query by:

Specifying the column from each table to be used for the join. A typical join condition specifies a foreign key from one table and its associated key in the other table. Specifying a logical operator (for example, = or <>,) to be used in comparing values from the columns. Inner joins can be specified in either the FROM or WHERE clauses. Outer joins can be specified in the FROM clause only. The join conditions combine with the WHERE and HAVING search conditions to control the rows that are selected from the base tables referenced in the FROM clause.

Follow this link to help you understand joins better in mssql: link to joins

相关问题