I have a standard bunch of products with a normal parent/child relationship table in a SQL Server database.
There are a set of products which have been modified, I want to be able to get these and their children and parents in a single record set, so I can perform some maintenance on their records. I know I could do this as 3 queries and UNION them but I was wondering if there was a better way to get them?
products TABLE
pid mod_date
----------------------
1 01-01-2023
2 20-01-2023
3 09-06-2023
4 01-01-2023
5 20-05-2023
6 09-06-2023
7 01-01-2023
parent_child TABLE
parent_pid child_pid
----------------------
1 2
3 4
5 6
5 7
With the following SQL
SELECT pid
FROM products
WHERE mod_date > dateAdd(day, -1, getdate())
UNION
SELECT pc1.child_pid
FROM products p
INNER JOIN parent_child pc1
ON pc1.parent_pid = p.pid
WHERE p.mod_date > dateAdd(day, -1, getdate())
UNION
SELECT pc2.parent_pid
FROM products p
INNER JOIN parent_child pc2
ON pc2.child_pid = p.pid
WHERE p.mod_date > dateAdd(day, -1, getdate())
(Assume that getdate() returns 2023-06-09)
Results:
3
4
5
6
Is there a more succinct way to get the same results, particularly when my where condition could get much more complicated (but would always be the same for each select statement)
3条答案
按热度按时间puruo6ea1#
You could shorten it a bit using CTE and make union once:
dbfiddle demo
col17t5w2#
You can move the union part to an apply:
cld4siwp3#
Try the following using a
left join
and theexists
operator:demo