I have the following tables:
Table A Table B
------------- -------------
| nameA| numA | | nameB| numB |
|-------------| |-------------|
| A | 3 | | z | 1 |
|------+------| |------+------|
| C | 9 | | w | 5 |
|------+------| |------+------|
| D | 7 | | y | 3 |
|------+------| |------+------|
| B | 2 | | x | 9 |
|------+------| |------+------|
I want to get the name columns of both tables where the number in the num column is the closest to some number without going over
I can easily create the queries for this independently but I do not know how to join the results.
For example if I want nameA where numA is closest to 5 without going over and nameB where numB is closest to 4 without going over I would have the 2 following queries
SELECT nameA FROM TableA WHERE numA < 5 ORDER BY numA LIMIT 1
SELECT nameB FROM TableB WHERE numB < 4 ORDER BY numB LIMIT 1
And the resulting table I would want would be
---------------
| nameA | nameB |
|---------------|
| A | y |
---------------
Just to note, TableA has about 100,000 rows and TableB has about 1,000,000 rows.
One method just prepends select
to the two queries:
select (select a.name
from a
where a.numA < 5
order by a.numA desc
fetch first 1 row only
) a_name,
(select b.name
from b
where b.numB < 5
order by b.numB desc
fetch first 1 row only
) b_name;
Or put this in the FROM
clause and use a CROSS JOIN
:
select a.*, b.*
from (select a.name
from a
where a.numA < 5
order by a.numA desc
fetch first 1 row only
) a CROSS JOIN
(select b.name
from b
where b.numB < 5
order by b.numB desc
fetch first 1 row only
) b
Try this:
select nameA, nameB
from TableA, TableB
where numA<5
and numB<4
order by numA desc, numB desc
fetch first 1 row only;
or if you want to use the newer "join" notation:
select nameA, nameB
from TableA
join TableB
on numA<5
where numB<4
order by numA desc, numB desc
fetch first 1 row only;
Result:
nameA nameB
a y
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.