我有2个表:tbl1
和tbl2
。我想从tbl1
返回单行,其列为:col1
,col2
,col3
,can_be_deleted
,have_important_items
。这个想法是can_be_deleted
和have_important_items
列是通过在同一表tbl2
中搜索而产生的布尔值。
SELECT
col1,
col2,
col3,
NOT EXISTS(SELECT 1 FROM tbl2 WHERE mycategory=10 AND status>0 LIMIT 1) AS can_be_deleted,
EXISTS(SELECT 1 FROM tbl2 WHERE mycategory=10 AND type_item>0 AND status>0 LIMIT 1) AS have_important_items
FROM tbl1 WHERE ... LIMIT 1
为避免日后澄清,tbl2
列为:
问题:我可以编写更快的查询吗?
答案 0 :(得分:0)
使用JOIN比EXIST快,请检查此查询是否解决了您的问题,如果不能解决,则只需更改条件即可获得结果。 “ t1.t2_id”是tbl2的外键,将其更改为正确的名称
SELECT
col1,
col2,
col3,
LEFT JOIN tbl2 AS t2 ON t2.id = t1.t2_id
WHERE t2.mycategory = 10
AND t2.status>0
AND t2.type_item>0
FROM tbl1 AS t1 WHERE ... LIMIT 1