我有两张桌子:
events and events_actions
events columns:
event_id
user_id
event_name
events_actions columns:
action_id
user_id
event_name
他们在两个表中都有一个公共字段,即event_name
我想显示用户的所有事件,但是,只有当他们有一些event_actions链接到它们时(由event_name链接)
我可以通过user_id拉出所有事件,然后在显示之前确保同名,event_actions> 0但有没有办法在一个SQL查询中执行此操作?
我正在使用MySQL
答案 0 :(得分:1)
select *
from events ev
where exists (select 1 from event_actions ea where ev.event_name = ea.event_name)
或
select ev.event_name,count(ea.action_id)
from events ev,event_actions ea
where ev.event_name = ea.event_name
group by ea.event_name
having count(ea.action_id) > 0
答案 1 :(得分:1)
首先,表event_id
上应该events_actions
,而不是event_name
。好吧,假设event_name
是唯一的,您可以执行以下查询:
SELECT E.user_id, E.event_name
FROM dbo.events E
INNER JOIN (SELECT DISTINCT event_name, user_id FROM dbo.events_actions) EA
ON E.user_id = EA.user_id AND E.event_name = EA.event_name