4

我正在使用单个 sql 从同一个表中的两个不同行中选择数据。

"id"    "borrowMax" "holder"    "category"  "country"
"1"     "2"         "0"         "3"         "US"
"2"     "0"         "1"         "10"        "US"

我正在努力解决这个问题。

select id, holder from mytable where id = 2
select borrowMax from mytable where id = (
        holder from the above select, in this case it's 1
) and category = 3

在网上查看示例后,我的做法是

SELECT col1.id, col1.holder, col2.borrowMax
FROM collection_db col1
JOIN collection_db col2
ON col2.holder = col1.id
WHERE col1.id = 2 //Here, 2 is the value supplied by me
AND col2.category = 3

当然,这行得通。但由于这是我自己拼凑的东西,我有我的怀疑。怎么会you做这样的事情?我在正确的轨道上吗?(我确定我不是)。

4

3 回答 3

3

您也可以为此使用表别名。

select t1.id, t1.holder, t2.borrowMax from mytable t1, mytable t2 where t1.id = t2.holder
于 2013-06-21T16:59:16.510 回答
1

I would make use of nested select statements for a use case like yours. There is no JOIN operation being used, just a select query over a already filtered set of results and a logically more coherent code.

SELECT borrowmax, holder, id FROM mytable WHERE 
  id = (SELECT holder FROM mytable WHERE id = 2 )
    AND category = 3
于 2013-06-21T19:14:56.060 回答
0

我必须找到印度尼西亚 2000 年和 2010 年的人口差异是多少?表列:

country STRING
population  NUMBER
year    NUMBER

这是给我我正在寻找的结果的查询:

SELECT b.country,
(b.population - a.population) 
AS diff_population
  FROM population_years a
  JOIN population_years b ON b.country = a.country
WHERE b.country = 'Indonesia'
  AND a.year = 2000
  AND b.year = 2010;
于 2020-09-25T18:48:05.507 回答