我有两张桌子reports
& viewedids
第一个存储数据,第二个存储查看数据的用户ID:
观察者:
+-------+------+
| uid | rid |
+-------+------+
| 2 | 5 |
+-------+------+
每个(uid
,rid
)表示uid
已查看rid
我想从*
表中选择reports
,并为当前用户添加视图状态(0
或1
)。 (A JOIN声明)
我怎么能这样做?
答案 0 :(得分:1)
您可以使用LEFT JOIN:
SELECT reports.*, viewedids.uid IS NOT NULL as view_state
FROM
reports LEFT JOIN viewedids
ON reports.id = viewedids.rid
AND viewedids.uid = @current_user
这将返回所有报告,并尝试加入带有已查看的报告表reports.id = viewedids.rid AND viewedids.uid = @current_user
。如果连接成功,则visitedids.uid将不为null,viewedids.uid IS NOT NULL
将被评估为1.否则将评估为0.
请参阅小提琴here。