从其他表添加视图状态以选择结果

时间:2013-06-24 22:40:12

标签: mysql sql join

我有两张桌子reports& viewedids
第一个存储数据,第二个存储查看数据的用户ID:

观察者:

+-------+------+
|  uid  | rid  |
+-------+------+
|   2   |   5  |
+-------+------+

每个(uidrid)表示uid已查看rid

我想从*表中选择reports,并为当前用户添加视图状态(01)。 (A JOIN声明)
我怎么能这样做?

1 个答案:

答案 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