Select records in on table based on conditions from another table?

前端 未结 2 886
日久生厌
日久生厌 2020-12-31 07:35

I have got 2 tables, A, B

A: id is primary key and indexed

id,  type_id,  status
------------------
1,  1,  True
2,  1,  False
3,  2,  False
...

B: (Type)          


        
相关标签:
2条回答
  • 2020-12-31 07:58

    I will do it in this way (it should be valid in most database systems:

    select *
    from b
    where type_id in (
      select type_id
      from a
      where status = true
    )
    

    To your question about if yours is a good way, my answer is no, it is not a good way because it likely forces a big intermediate record set (by the joining) then a time consuming distinct on the intermediate record set.

    UPDATE

    After some thought I realized there is no absolute good or bad solution. It all depends on the data your have in each table (total records, value distribution, etc...). So go ahead with the one that is clearly communicate the intention and be prepared to try different ones when you hit a performance issue in production.

    0 讨论(0)
  • 2020-12-31 08:05
    SELECT B.*
    FROM B
    WHERE B.type_id
    IN 
    ( SELECT A.type_id 
      FROM A WHERE status='True'
    );
    
    0 讨论(0)
提交回复
热议问题