我有表用户,事件(公共,私人或秘密类型),服务员,组织者,我需要选择用户1是服务员的所有事件或组织者除了秘密事件,其中用户2不是(参加组织者)或邀请)。
这个巨大的SELECT完成了我所需要的一切,但它包含许多其他SELECT。 是否可能以某种方式对其进行优化就像把这个联盟与这里的评论接壤 - 在这里使用某种变量并重新使用它?
编辑:我当时需要能够完成更多这些请求。
SELECT `event`.id AS eventid, event.name AS ename
FROM attendant
INNER JOIN user ON attendant.fk_user = user.id
INNER JOIN event ON attendant.fk_event = `event`.id
WHERE user.id = 2
AND attendant.fk_event = `event`.id
AND `event`.id IN
-- FROM HERE
(
SELECT `event`.id
FROM attendant
INNER JOIN user ON attendant.fk_user = user.id
INNER JOIN event ON attendant.fk_event = `event`.id
WHERE user.id = 1
AND attendant.fk_event = `event`.id
UNION
SELECT `event`.id
FROM organizer
INNER JOIN user ON organizer.fk_user = user.id
INNER JOIN event ON organizer.fk_event = event.id
WHERE user.id = 1
AND organizer.fk_event = event.id
UNION
SELECT `event`.id
FROM invitation
INNER JOIN user ON invitation.fk_user_to = user.id
INNER JOIN event ON invitation.fk_event = event.id
WHERE invitation.fk_user_to = 1
AND invitation.fk_event = event.id)
-- TO HERE
UNION
SELECT `event`.id AS eventid, event.name AS ename
FROM organizer
INNER JOIN user ON organizer.fk_user = user.id
INNER JOIN event ON organizer.fk_event = event.id
WHERE user.id = 2
AND organizer.fk_event = event.id
AND `event`.id IN
(
-- FROM HERE
SELECT `event`.id
FROM attendant
INNER JOIN user ON attendant.fk_user = user.id
INNER JOIN event ON attendant.fk_event = `event`.id
WHERE user.id = 1
AND attendant.fk_event = `event`.id
UNION
SELECT `event`.id
FROM organizer
INNER JOIN user ON organizer.fk_user = user.id
INNER JOIN event ON organizer.fk_event = event.id
WHERE user.id = 1
AND organizer.fk_event = event.id
UNION
SELECT `event`.id
FROM invitation
INNER JOIN user ON invitation.fk_user_to = user.id
INNER JOIN event ON invitation.fk_event = event.id
WHERE invitation.fk_user_to = 1
AND invitation.fk_event = event.id);
-- TO HERE
答案 0 :(得分:1)
我建议创建视图以获取中间结果并重用它们。
视图很便宜:数据未存储,您可以在选择中使用它们。
在你的情况下作为一个小例子:
create view viewname_1 as SELECT
event
.id
FROM invitation
INNER JOIN user ON invitation.fk_user_to = user.id
INNER JOIN event ON invitation.fk_event = event.id
WHERE invitation.fk_user_to = 1
AND invitation.fk_event = event.id
AND
(event
.type = 'secret'
OR event
.type = 'private'
OR event
.type = 'public')
)`
稍后使用viewname_1作为select * from viewname_1 ...
显然,您可以为视图选择自己的命名约定:只需注意命名空间。