I have two tables in my database Table A And Table B –
Table `A`
SN | Order1 | Order2 | Text
(INT) | (TINYINT) | (TINYINT) | (VARCHAR)
1001 | 1 | 1 | ABC
1001 | 1 | 2 | DEF
1001 | 1 | 3 | GHI
1001 | 2 | 1 | IOU
1001 | 3 | 1 | JKL <--
1001 | 3 | 2 | LMO
1001 | 3 | 3 | UTF
....
1021 | 1 | 1 | ZXC
1021 | 1 | 2 | QWE
1021 | 2 | 1 | JKL <--
1021 | 3 | 1 | YOU
And In Another Table
Table `B`
SN | Order1 | rSN | rOrder1
1021 | 2 | 1001 | 3
Now when I query for the data of 1021 the result should be like :-
Result Needed
1 | 1 | ZXC
1 | 2 | QWE
2 | 1 | JKL
2 | 2 | LMO
2 | 3 | UTF
3 | 1 | YOU
Presently I am trying somthing Like this –
SELECT `SN`, `Order1`, `Order2`, `Text` FROM `Table A`
WHERE `SN`=1012
UNION
SELECT `SN`, `Order1`, `Order2`, `Text` FROM `Table A`
WHERE `Table A`.`SN`
IN (SELECT `rSN` FROM `Table B` WHERE `SN`=1021)
AND `Table A`.`Order1`
IN (SELECT `Order1` FROM `Table B` WHERE `SN`=1021)
Which Is giving the Results Like this :-
Result
SN | Order1 | Order2 | Text
1021| 1 | 1 | ZXC
1021| 1 | 2 | QWE
1021| 2 | 1 | JKL
1021| 3 | 1 | YOU
1001| 3 | 1 | JKL
1001| 3 | 2 | LMO
1001| 3 | 3 | UTF
What should I do to get the Order1 and Order2 of the last three rows of the result be same as the referring Row i.e. like 1001 | 2 | 2 | LMO
Edit —
Here I am Thinking to get the Order1 values of the 1001 to be same as Order1 of 1012 when query gives the data output.
As The Order Of the Text Is important.
The Order2 Text is related to its corresponding first value in this Group In Order1
And Table B Stores reference to the already entered duplicate related Text in the database and defines its position in the corresponding SN
I found the solution myself : –
Solution
Explanation
The First
SELECTSelects theRowsassociated with1021In Second Part of query, I wanted the
TextOf the referredSNi.e.1001‘s row’s havingOrder1value3(See Table B).But as the referring
SNi.e.1021have itsOrder1value2, WHERE its Text isJKL(See Table A, Pointed Row (“<–“) with 1021 SN)So We want All the values of
Order1of Text associated with1001 | 3 |Formatted As1001 | 2 |For this above problem
JOINWorks, Joining gives a table like :-And From this result we can Pick up the result set.
Understanding how
2, 2, LMOcomes -> It is here Now we are picking up theTable B.Order1From the JOIN result Instead like earlier we were Picking up theOrder1Of the1001instead, which then results into ordering which we didn’t wanted.why isn't 1, 3, GHI required as a part of result-> As Its Like Related Information,The Information with same
Order1show the related words/information to each other and since1021Do not have any related information to1, 3, GHIHence It is not required in the result part.And as Now we already getting the
Order1of the second query same as it should be2not3We can now easily Order Them by Order clauseI hope this will clarify the question also.
Still Thanks everyone 🙂
—— EDIT ——-
DISTINCTin UNION will remove the Duplicate Entry ofJKLFrom the final results