[英]Select records in on table based on conditions from another table?
我有2張桌子,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
我想選擇B
中的所有行,其中A
中至少有1個關聯條目, status True
select distinct B.id, B.param
from B
join A on A.type_id = B.type_id
where A.status = true
這是一個好方法嗎?
我會這樣做(它應該在大多數數據庫系統中有效:
select *
from b
where type_id in (
select type_id
from a
where status = true
)
對於你的問題是否是一個好方法,我的答案是否定的,這不是一個好方法,因為它可能會強制設置一個大的中間記錄集(通過加入),然后在中間記錄集上耗費時間。
UPDATE
經過一番思考后,我意識到沒有絕對好的或壞的解決方案。 這完全取決於您在每個表中的數據(總記錄,價值分布等)。 因此,繼續明確表達意圖並准備在生產中遇到性能問題時嘗試不同的意圖。
SELECT B.*
FROM B
WHERE B.type_id
IN
( SELECT A.type_id
FROM A WHERE status='True'
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.