SQL help

Looking for help on whether the following query can be simplified.

Basically it's
Select records From A
Union
Select records From B WHERE records NOT IN (Select records From A)

Can I more easily write this without effectively duplicating the select on A

Code:
		SELECT		s.id AS SYSTEMID, s.NAME AS SYSTEMNAME, t.ID AS TEAMID, t.NAME AS TEAMNAME,
					t.ISFIRSTLINE, t.NATIONALSERVICETEAM, tu.DEFAULTTEAM
		FROM		TBLCLTEAMUSER tu WITH (NOLOCK)
					INNER JOIN	TBLCLTEAM t WITH (NOLOCK) ON tu.TEAMID = t.ID 
					INNER JOIN	TBLCLSYSTEM s WITH (NOLOCK) ON t.SYSTEMID = s.ID
		WHERE		t.ACTIVE = 1
			AND		tu.USERID = @userid
				
					
	UNION
		
		SELECT		s.id AS SYSTEMID, s.NAME AS SYSTEMNAME, t.ID AS TEAMID, t.NAME AS TEAMNAME,
					t.ISFIRSTLINE, t.NATIONALSERVICETEAM, 0 AS DEFAULTTEAM
		FROM		TBLCLTEAM t 
					INNER JOIN	TBLCLSYSTEM s WITH (NOLOCK) ON t.SYSTEMID = s.ID
		WHERE		t.ACTIVE = 1
			AND		(	
						-- inherit teams in system if user is a member of a 1st line team in system
						t.SYSTEMID IN 			
							(SELECT		t.SYSTEMID
							 FROM		TBLCLTEAMUSER AS tu WITH (NOLOCK)
										INNER JOIN TBLCLTEAM AS t WITH (NOLOCK) ON tu.TEAMID = t.ID
							 WHERE      tu.USERID = @userid
								AND		t.ACTIVE = 1
								AND		t.ISFIRSTLINE = 1)
						OR	
						
						-- inherit teams in system if user is system admin in system
						t.SYSTEMID IN 			
							(SELECT		SYSTEMID
							 FROM		TBLCLSYSTEMADMIN WITH (NOLOCK)
							 WHERE      USERID = @userid
								AND		SYSTEMADMIN = 1)
							
					)
					
					-- but don't create duplicate with actual granted permissions
			AND		t.ID NOT IN 
						(SELECT	t.ID 
						 FROM	TBLCLTEAMUSER tu WITH (NOLOCK)
								INNER JOIN	TBLCLTEAM t WITH (NOLOCK) ON tu.TEAMID = t.ID 
						 WHERE	t.ACTIVE = 1
						 AND		tu.USERID = @userid)
								
		
					
				
					
					
	ORDER BY	SYSTEMNAME, TEAMNAME
 
Took a look at that, don't think it's what I want, or at least it needs a bit more configuration.

Except - "Returns any distinct values from the query to the left of the EXCEPT operator that are not also returned from the right query"

I need all the rows from the left (first query) plus those from the right (second) that are not already in the left (first)
 

Jehos

Ars Legatus Legionis
55,560
UNION auto-excludes duplicates. You don't need to check whether you already have the records in the first query, SQL does that for you.

You use UNION ALL if you want to keep the duplicates.

Note, this is exact match dupes, meaning every column is the same value for both rows.

Also, don't use IN / NOT IN. You can do those with joins and it'll potentially be faster (less chance of confusing SQL).

Code:
SELECT foo 
FROM bar 
WHERE baz IN (
  SELECT baz 
  FROM bam 
  WHERE frobbits = 1
)

is exactly the same as

Code:
SELECT foo 
FROM bar 
INNER JOIN bam 
  ON bar.baz = bam.baz 
  AND bam.frobbits = 1

For NOT IN, use LEFT OUTER JOIN and check for nulls.

Code:
SELECT foo 
FROM bar 
LEFT OUTER JOIN bam 
  ON bar.baz = bam.baz 
  AND bam.frobbits = 1
WHERE bam.baz IS NULL

That's equivalent to

Code:
SELECT foo 
FROM bar 
WHERE baz NOT IN (
  SELECT baz 
  FROM bam 
  WHERE frobbits = 1
)

If you have other SQL problems, best to ask them in the Programmer's Symposium, probably in the while(true) thread (it's the generic catch-all discussion)
 

dodexahedron

Ars Praefectus
3,368
Subscriptor++
Then yes. UNION is all you need, because UNION operates on unique values.
As said above, that means all columns in your select statement must be identical for the duplicates to be eliminated.


If you have the following:


T1:

Code:
col1   col2   col3
Item1  1       1
Item2  2       2
Item3  3       3
T2:

Code:
col1   col2   col3
Item1  1      1
Item3  3      2

And you run this query:

Code:
SELECT col1, col2, col3 FROM T1
UNION
SELECT col1, col2, col3 FROM T2

You will get:

Result:

Code:
col1   col2   col3
Item1  1      1
Item2  2      2
Item3  3      3
Item3  3      2

Note you get 4 records, since Item3 wasn't identical for all columns in both tables.

If you only did this:

Code:
SELECT col1 FROM T1
UNION
SELECT col1 FROM T2
You'd get:

Code:
col1
Item1
Item2
Item3

There are 3 results, because Item3 is no longer unique, for that select statement.

UNION ALL will return all results, regardless, which is, of course, exactly what you don't want.
 
Union does what I want, to a point. I need the DEFAULTTEAM value set and, as a result, get two values for the one record if I don't specifically exclude it at the end.

The first query gets the records, one of which will have a defaultteam of 1. The second query needs to add the other records but these will have an explicit defaultteam team of 0 - but this will also include the one record from the first but now with 0, which I need to exclude.
 

Jehos

Ars Legatus Legionis
55,560
Union does what I want, to a point. I need the DEFAULTTEAM value set and, as a result, get two values for the one record if I don't specifically exclude it at the end.

The first query gets the records, one of which will have a defaultteam of 1. The second query needs to add the other records but these will have an explicit defaultteam team of 0 - but this will also include the one record from the first but now with 0, which I need to exclude.
So take DEFAULTTEAM out of your result set and UNION will do the job.

If you need it in there and are getting dupes, you have a data problem where you have the same entity with DEFAULTTEAM of both 0 and 1.
 
The context of the data requirement means it is perfectly logical and not a data issue, can't take that field out since it's required.

Basically, the first query gets a set of explicit permissions for a user (a list of teams they have permission to), the defaultteam will be true for one of the values but false for all the others.

However, depending on other permissions (whether they are an admin or 1st line team member) then they also get permissions to the other teams even if they don't have explicit permission to them set. Because they don't have explicit permissions to these additional teams then there will be no userteam record and therefore no defaultteam value so these all need to have the defaultteam value defaulted to 0 by the query.

However, this may result in the one positive record from the first query that they do have explicit access to being duplicated in the union (because of the default 0 value) so needs to be excluded. Hence my query... :)
 

Jehos

Ars Legatus Legionis
55,560
OK, so I agree that doesn't sound like a data issue. Here's a super duper simplified query:

Code:
SELECT User, Group, Default FROM AssignedMembership
UNION
SELECT User, Group, 0 FROM ImplicitMembership

As long as you don't have a user who is both assigned a team and that team is default AND they implicitly pick up a team, you're good.

Slightly more complex if you need it, you can just query out the default teams for each user and exclude those.

Code:
SELECT
  User, Group, Default
FROM
  AssignedMembership

UNION

SELECT
  User, Group, 0
FROM
  ImplicitMembership i
  LEFT OUTER JOIN AssignedMembership a
    ON i.User = a.User
    AND i.Group = a.Group
    AND a.Default = 1
WHERE
  a.User IS NULL

The second query in the union above pulls all the implicit group membership but excludes the user/group intersection where they're explicitly assigned that group as their default. It does that by a LEFT OUTER JOIN that basically picks up all the default group memberships (your problem children in the data) and ensures that they're not in the result set with the WHERE clause. You could have the same non-default group membership in both queries within the UNION, but SQL will auto-filter those out.
 

Jehos

Ars Legatus Legionis
55,560
Many thanks

As long as you don't have a user who is both assigned a team and that team is default AND they implicitly pick up a team, you're good.

That is the issue unfortunately. I need to return all teams but that will include those with the explicit permission, hence the reason to exclude.
In that case you need this:

Code:
SELECT User, Group, MAX(Default) 
FROM (
  SELECT User, Group, Default FROM AssignedMembership
  UNION
  SELECT User, Group, 0 FROM ImplicitMembership
) A
GROUP BY User, Group
 

dodexahedron

Ars Praefectus
3,368
Subscriptor++
Many thanks

As long as you don't have a user who is both assigned a team and that team is default AND they implicitly pick up a team, you're good.

That is the issue unfortunately. I need to return all teams but that will include those with the explicit permission, hence the reason to exclude.
In that case you need this:

Code:
SELECT User, Group, MAX(Default) 
FROM (
  SELECT User, Group, Default FROM AssignedMembership
  UNION
  SELECT User, Group, 0 FROM ImplicitMembership
) A
GROUP BY User, Group

Bah.
Use CTEs, people.
Sub-queries are so...non-hipster (in all seriousness, though, they do make a lot of things simpler to visually parse and simplify otherwise very difficult queries into trivial constructs).

Code:
WITH UnionedDataSet AS --The name here can be whatever you want. I just went with something that made it obvious what it was... You could also call it 'A' like the above example, if you hate your coworkers. ;)
(
  SELECT User, Group, Default FROM AssignedMembership
  UNION
  SELECT User, Group, 0 FROM ImplicitMembership
)
SELECT User, Group, MAX(Default)
FROM UnionedDataSet
GROUP BY User, Group

Only reason I'm pointing it out here is because I bet you're going to end up wanting to do joins and stuff on this and that it'll ultimately end up as a more complex query than what's being discussed here, and this syntax will make life easier later on.
Sub-queries are only valid within the context of an expression.
CTEs are valid for an entire query and may as well just be a table. Plus, you can do more than one in a single "query," if you want.
It can turn a giant spaghetti-SQL query into well-defined blocks and a single, simple, query, at the end.