First I have to run the query (1) using the pagedetailid
number to get the adblockid
. Then I have to put that adblockid
into the other query (2) to get the result. What I would prefer is a single query.
select distinct Flyerid, adblockid, OriginalPagedetailid, Pagedetailid, category, brand, [Sales Price], Size, Format, manufacturer from prdcnen where pagedetailid = '67197228466'
select distinct Flyerid, adblockid, OriginalPagedetailid, Pagedetailid, category, brand,[Sales Price], Size, Format, manufacturer from prdcnen where Adblockid = 1521368536511158
How can I merge these two statements?
John K. N.
18.9k14 gold badges56 silver badges117 bronze badges
asked Aug 2, 2018 at 11:41
2 Answers 2
One possible way is an inner self join.
SELECT DISTINCT
p1.Flyerid,
p1.adblockid,
p1.OriginalPagedetailid,
p1.Pagedetailid,
p1.category,
p1.brand,
p1.[Sales Price],
p1.Size,
p1.Format,
p1.manufacturer
FROM prdcnen p1
INNER JOIN prdcnen p2
ON p2.Adblockid = p1.Adblockid
WHERE p2.pagedetailid = '67197228466';
answered Aug 2, 2018 at 11:56
In it's simplest form you can just replace the literal for adblockid with a query:
SELECT distinct Flyerid, adblockid, OriginalPagedetailid, Pagedetailid
, category, brand,[Sales Price], Size, Format, manufacturer
FROM prdcnen
WHERE adblockid = (select distinct adblockid
from prdcnen
where pagedetailid = '67197228466')
answered Aug 2, 2018 at 12:02
-
There is no guarantee the
adblockid
is unique for eachpagedetailid
. I think you must useLIMIT 1
instead ofDISTINCT
. Or... WHERE adblockid = SOME (select ...
Akina– Akina2018年08月02日 12:09:37 +00:00Commented Aug 2, 2018 at 12:09 -
@Akina, if it's not unique the question does not make sense. We would then have to choose an adblockid by some criteria, but none is given.Lennart - Slava Ukraini– Lennart - Slava Ukraini2018年08月02日 13:10:00 +00:00Commented Aug 2, 2018 at 13:10
-
DISTINCT
could still return multiple rows, so that is not a solution. Also,DISTINCT
is slower than simplyLIMIT 1
.Rick James– Rick James2018年08月20日 14:53:32 +00:00Commented Aug 20, 2018 at 14:53
lang-sql