2010-07-12 112 views
0

對不起,因爲這是一個菜鳥問題。我是新與MySQL:這個MySQL查詢有什麼問題?

我寫這樣的查詢:

SELECT 
    u.userid, u.alias, g.company_name, 
v.endtime - v.begintime AS duration, 
    u.status, u.service_starttime, 
u.service_expiretime, v.begintime, u.email 
FROM 
    company_users c, company_groups g INNER JOIN 
    user_info u INNER JOIN vfon_log v 
    ON (u.userid = v.hostid) ON (g.company_id = u.company_id) 

該查詢返回一個語法錯誤:

Query : SELECT  u.userid, u.alias, g.company_name, v.endtime - v.begintime AS duration, u.status, u.service_starttime, u.service_ex... 
Error Code : 1064 
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ON (g.company_id = u.company_id) 
LIMIT 0, 1000' at line 4 
Execution Time : 00:00:00:000 
Transfer Time : 00:00:00:000 
Total Time  : 00:00:00:000 

我花了30分鐘找,但我可以弄清楚什麼是錯的。

非常感謝你對你的幫助

+1

由於您正在使用MySQL,您可能需要將'v.endtime - v.begintime'更改爲'TIMEDIFF(v.endtime,v.begintime)AS duration',因爲這會給您一個正確格式化的時差。 – Mike 2010-07-12 08:46:40

回答

2
ON (g.company_id = u.company_id) 

後應INNER JOIN user_info u

,使其成爲

SELECT 
    u.userid, u.alias, g.company_name, 
v.endtime - v.begintime AS duration, 
    u.status, u.service_starttime, 
u.service_expiretime, v.begintime, u.email 
FROM 
    company_users c, company_groups g 
INNER JOIN user_info u ON (g.company_id = u.company_id) 
INNER JOIN vfon_log v ON (u.userid = v.hostid) 
0

我覺得應該b

SELECT  u.userid, u.alias, g.company_name, v.endtime - vbegintime AS duration, 
u.status, u.service_starttime, u.service_expiretime, v.begintime, u.email 
    FROM company_users c, company_groups g 
          INNER JOIN 
          (user_info u INNER JOIN vfon_log v ON (u.userid = v.hostid)) 
           ON g.company_id = u.company_id 
+0

我想這一點,但: 錯誤代碼:在 '字段列表' 執行時間1054 未知列 'vbegintime':00:00:00:000 轉換時間:00:00:00:000 總時間: 00:00:00:000 事實上,我沒有寫這個查詢。 Visual Studio根據我寫的查詢自動生成查詢 – Vimvq1987 2010-07-12 08:25:38

+0

Chris Diver的答案可能更接近期望的結果。 – 2010-07-12 08:26:28

1

你把ON聲明放在錯誤的地方。標準的解決辦法是將它添加後直接加入:

SELECT * 
    FROM company_users c, 
     company_groups g INNER JOIN 
      user_info u ON (g.company_id = u.company_id) 
     INNER JOIN vfon_log v 
       ON (u.userid = v.hostid) 

或者你可以用括號來得到正確的ON鏈接到正確的INNER JOIN

SELECT * 
    FROM company_users c, 
     company_groups g INNER JOIN 
      (user_info u INNER JOIN vfon_log v 
       ON (u.userid = v.hostid)) 
      ON (g.company_id = u.company_id) 
+0

第二個查詢有效(我正在檢查它是否正常工作,第一個查詢失敗:) – Vimvq1987 2010-07-12 08:31:35

+0

@ Vimvq1987:第一個查詢可能失敗,因爲最後一個INNER JOIN末尾有一個額外的''''。還要注意,在'FROM'子句中引用了表'company_users',但是在查詢的其他地方沒有使用。 – Mike 2010-07-12 08:35:55

+1

對不起,複製和粘貼沒有想到。我刪除了額外的支架,它現在應該工作。 – Matijs 2010-07-12 08:42:55

1

你的領域是不是vbegintimev.begintime

+0

只看到它:)。但糾正後,問題仍然存在 – Vimvq1987 2010-07-12 08:36:33

+0

邁克的評論可能會解決您的問題 – Toto 2010-07-12 08:58:34