我有两张桌子:
alerts {id, title, description}
read_alerts {alert_id}
我想执行一个返回以下内容的sql:
alerts {id, title, description, is_read}
is_read
必须为1
或0
。如果id在read_alerts
中设置,则为1,否则为0。
在一个SQL查询中实现此目的的最佳方法是什么?
我正在使用Sqlite
答案 0 :(得分:0)
我会在select
子句中使用子查询:
select a.*
(case when exists (select 1 from read_alerts ra where ra.alert_id = a.id)
then 1 else 0
end) as is_read
from alerts a;
在select
子句中使用子查询的关键原因是因为您没有指定read_alerts
是否可以有多行。无论read_alerts
的内容如何,此版本的查询都会保证每个警报一行。
答案 1 :(得分:0)
这可以通过外部联接来完成:
SELECT a.id,
a.title,
a.description,
ra.id IS NOT NULL AS is_read
FROM alerts AS a
LEFT JOIN read_alerts AS ra on a.id = ra.alert_id;
或使用相关子查询:
SELECT id,
title,
description,
EXISTS (SELECT 1
FROM read_alerts
WHERE alert_id = alerts.id
) AS is_read
FROM alerts;
答案 2 :(得分:0)
SELECT id, title, description, (CASE WHEN read_alert is not null THEN 1 else 0) as is_read
FROM alerts, read_alerts;