2012-09-25 54 views
0

問題:兩個表,第一個包含userid(約束fk)和列'name',第二個表包含兩列int和id(外鍵),我需要的是查找max(column1-第2列),並從第一個表中爲其分配名稱;mysql複雜語句

我在做什麼: 的mysql>

select u.name, MAX(table2.column1-table2.column2) As var 
    from table1 u, table2 b 
where u.userID(from table1) = b.userID(from table2) 
    and (b.column1-b.column2) = var; 

在這種情況下,它說: 「未知列VAR」,是有可能觸發withoud /程序?

enter image description here

ANY1?:)

+0

你試過用'MAX(table2.column1-是table2.column2)'你的WHERE子句中取代'var'? – Crontab

+0

複雜的聲音太多了! –

+0

多數民衆贊成你的要求?你試圖找到每個名字的最大值?在你的陳述中沒有分組? – RomanKonz

回答

0

也許嘗試一個子查詢呢?

select u.name, (b.column1 - b.column2) as var 
    from table1 u, table2 b 
where u.userID(from table1) = b.userID(from table2) 
    and (b.column1-b.column2) = (select MAX(column1 - column2) from table2); 
+0

THAAANK你:))))這一個是解決方案。讚賞 –

0

我認爲這是正確的解決方案:

select u.name, 
    MAX(table2.column1-table2.column2) As var 
from table1 u 
    join table2 b 
     on b.userId = u.userId 
where u.userID(from table1) = b.userID(from table2) 
group by u.name 
+0

好吧,它沒有帶我到我想要的地方2反正謝謝你的迴應,我只是將它加載到ResultSet中,並在程序端管理它;]感謝4個回覆。 –

+0

現在我明白了(我以前沒有看到圖片),是否適合您的解決方案? – RomanKonz