[英]SQL JOIN: How to echo values of a column of table A with same name as a column of table B?
[英]How to join same table to check if a>b with 10
表mytable
id numbers whereonly
1 2 1
2 35 1
3 22 1
4 20 1
5 3 1
6 70 1
7 80.15925 1
8 60 7
9 50 7
我需要按數字排序並以ID 1進行搜索,直到找到一個ID,其ID的數字行大10。
期望的結果:2,20,35,70,80.15925
僅在列whereonly為1的地方
有沒有辦法做到這一點?
您可以嘗試一下:
SELECT DISTINCT t1.id AS id, t1.numbers AS numbers
FROM table AS t1
INNER JOIN table AS t2 ON t1.numbers > t2.numbers - 10
WHERE t1.whereonly = 1
GROUP BY t2.numbers
ORDER BY t1.numbers;
這是sqlfiddle 。
編輯1: 草莓建議
SELECT DISTINCT x.*
FROM mytable x
JOIN
( SELECT t2.numbers t2n
, MIN(t1.id) id
FROM mytable t1
JOIN mytable t2
ON t1.numbers > t2.numbers - 10
GROUP
BY t2.numbers
) y
ON y.id = x.id
ORDER BY x.numbers
WHERE x.whereonly = 1;
這是sqlfiddle 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.