我的加入在它应该工作时失败了

时间:2013-05-24 12:58:02

标签: mysql

这只是一个简单的连接,但为什么会失败呢?

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

我实际上是想把这两个sqls合二为一。

select id, holder from mytable where id = 2
select borrowMax from mytable where id = (holder from the above select) and category = 10

我是怎么做的

SELECT col1.id, col1.holder, col2.borrowMax
FROM collection_db col1
JOIN collection_db col2
ON col2.holder = col1.id
WHERE col1.id = 2 //2 = Value supplied by me
AND col2.category = 10

结果我想要:

"id"    "holder"    "borrowMax"
"2" "1" "2"

2 个答案:

答案 0 :(得分:2)

我认为结果是正确的

col2.holder = col1.id will give 

"id"  "borrowMax" "holder"    "category"  "country"
 1         ....     1  ...........................

然后另一个条件是col1.id = 2

这里没有2的记录。所以你没有得到任何记录

答案 1 :(得分:1)

在JOIN ON子句中给出列名时,请认为你的表名是错误的: -

SELECT col1.id,col1.holder,col2.borrowMax FROM collection_db col1 JOIN collection_db col2 ON col1.holder = col2.id 在哪里col1.id = 2 // 2 =我提供的价值 AND col2.category = 10