基本上我有4个表和当前组的组ID。 我将列出重要的字段和信息:
Users:
ID,
FirstName,
LastName
Groups:
ID,
participantlist_id
participantlist:
list_id
participantlist_links:
list_id,
participant_id
我已经想出如何在树的最高点显示参与者list.list_id中的所有用户,但功能有点:
SELECT Users.ID,Users.FirstName,Users.LastName FROM Users
JOIN participantlist_links ON Users.ID = participantlist_links.participant_id
JOIN participantlist ON participantlist_links.list_id = participantlist.list_id
JOIN Groups ON participantlist.list_id = Groups.participantlist_id AND
Groups.ID = '".workspaces_tell_me_brainstorm_group_id_from_group_id($group_id)."'
现在我想排除链接到当前组($ group_id)的participantlist.list_id的所有用户,但我无法找到在单个查询中完成所有操作的好方法。我认为解决方案将是某种左连接/右或左/右外连接比较。
我的工作暂时,但非常耗时的解决方案是:
SELECT table2.id as ID, table2.firstname as FirstName, table2.lastname as LastName
FROM
(SELECT table1.ID,table1.FirstName,table1.LastName FROM Users as table1
JOIN participantlist_links ON table1.ID = participantlist_links.participant_id
JOIN participantlist ON participantlist_links.list_id = participantlist.list_id
JOIN Groups ON participantlist.list_id = Groups.participantlist_id
AND Groups.ID = '".workspaces_tell_me_brainstorm_group_id_from_group_id($group_id)."')
as table2
LEFT JOIN
(SELECT table4.ID,table4.FirstName,table4.LastName FROM Users as table4
JOIN participantlist_links ON table4.ID = participantlist_links.participant_id
JOIN participantlist ON participantlist_links.list_id = participantlist.list_id
JOIN Groups ON participantlist.list_id = Groups.participantlist_id
AND Groups.ID = '".$group_id."')
as table3
ON table2.ID = table3.ID WHERE table3.id is null
有什么建议吗?
答案 0 :(得分:1)
我会选择更简单的东西。
我认为not in
是你的朋友。它应该让你的代码更容易阅读,并且很可能让mysql更优化它:
SELECT table1.ID,
table1.FirstName,
table1.LastName
FROM Users as table1
JOIN participantlist_links ON table1.ID = participantlist_links.participant_id
JOIN participantlist ON participantlist_links.list_id = participantlist.list_id
JOIN Groups ON participantlist.list_id = Groups.participantlist_id
AND Groups.ID = '".workspaces_tell_me_brainstorm_group_id_from_group_id($group_id)."')
AND table1.id not in (
SELECT table4.ID
FROM Users as table4
JOIN participantlist_links ON table4.ID = participantlist_links.participant_id
JOIN participantlist ON participantlist_links.list_id = participantlist.list_id
JOIN Groups ON participantlist.list_id = Groups.participantlist_id
AND Groups.ID = '".$group_id."'
)