简体   繁体   中英

SQL join 2 tables, query 1st with condition from 2nd

I have 2 tables:

Downtime Categories: CatID ----- CatName ----- SiteID

Downtimes: DtID ----- DtName ----- CatID

How do I create a query so I can pull all of the records from Downtimes where the SiteID from Downtime Categories = x?

I don't know how to word this search to get what I need, I have tried all the Joins but none of them give me what I'm after

Any help would be appreciated, thanks

Edit: I have tried all variants of the below answers but none of them worked... copying one into SMS and running it now worked first time :( I must have had a typo somewhere...stupid... Thanks for the replies

SELECT D.* FROM
DOWNTIMES D INNER JOIN DOWNTIMECATEGORIES DC ON (D.CATID = DC.CATID)
WHERE DC.SiteID = X

Try this:

SELECT T1.CatID
      ,T1.CatName
      ,T1.SiteID
FROM Downtimes AS T1
INNER JOIN DowntimesCategories AS T2
    ON T1.CatID = T2.CatID
WHERE T2.SiteID = X

Try Inner join as below:

SELECT *
FROM DOWNTIME_CATEGORIES DC INNER JOIN DOWNTIME D
ON D.CatId = DC.CatID
WHERE DC.SiteID = 'X'

Looks Like simple INNER JOIN is what you need

SELECT *
FROM   Downtime_Categories DC
       JOIN Downtimes D
         ON DC.CatID = D.CatID
            AND DC.SiteID = 'x' 

This is what I came up with:

Select d.*
From Downtime d
Inner Join DowntimeCategories dc On dc.CategoryId = d.CategoryId
  And dc.SiteId = x

You can try this

SELECT D.CatID ,D.CatName ,D.SiteID
FROM Downtimes D INNER JOIN DowntimesCategories DC
    ON D.CatID = DC.CatID
WHERE DC.SiteID = put your id here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM