Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

sql

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) type_id is primary key and indexed

type_id, param
----------
1,  23
2,  35
3,  24

I would like select all rows in B which has at least 1 associated entry in A with status True

select distinct B.id, B.param 
from B
join A on A.type_id = B.type_id
where A.status = true

Is this a good way?

like image 420
colinfang Avatar asked Oct 03 '13 15:10

colinfang


People also ask

How do I get data from another table in SQL?

In SQL, to fetch data from multiple tables, the join operator is used. The join operator adds or removes rows in the virtual table that is used by SQL server to process data before the other steps of the query consume the data.

How do I SELECT a column from another table in SQL?

Syntax: SELECT * FROM table_name WHERE column_name=( SELECT column_name FROM table_name); Query written after the WHERE clause is the subquery in above syntax. we can use the following command to create a database called geeks.

How do you SELECT all records from one table that do not exist in another table in SQL Server?

How to Select All Records from One Table That Do Not Exist in Another Table in SQL? We can get the records in one table that doesn't exist in another table by using NOT IN or NOT EXISTS with the subqueries including the other table in the subqueries.


2 Answers

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.

like image 125
Codism Avatar answered Sep 21 '22 17:09

Codism


SELECT B.*
FROM B
WHERE B.type_id
IN 
( SELECT A.type_id 
  FROM A WHERE status='True'
);
like image 27
Teja Avatar answered Sep 19 '22 17:09

Teja