2014-01-10 60 views
-1

我試圖選擇機器和kpi的每個人使用的列表。查詢使用3表

KPIs 
- id  ('123') 

MACHINE 
- id  ('567') 

KPIDATA 
- key  ('k.123.i.567.a.000') 

KPIDATA行說,機567使用KPI 123。如何在一個查詢中選擇這個?

+0

將在KPI和機械錶中的ID僅爲3位數的ID –

+0

此修正格式'k.123.i.567.a.000' – DevelopmentIsMyPassion

回答

1

假設你有相同的格式爲Kpidata key領域,即像k.123.i.567.a.000

此查詢可以幫助

SELECT 
     k.`id`, 
     m.`MACHINE`, 
     kd.`key` 
FROM 
     KPIs as k, 
     MACHINE as m, 
     KPIDATA as kd 
WHERE 
     k.`id` = SUBSTR(kd.`key`,LOCATE('.',kd.`key`)+1,3) 
AND 
     m.`MACHINE` = SUBSTR(kd.`key`,LOCATE('.i.',kd.`key`)+3,3) 

工作演示在http://sqlfiddle.com/#!2/7d814b/17

0
SELECT k.id AS key, m.id AS machine 
FROM KPIs k, MACHINE m 
WHERE EXISTS ( 
    SELECT 1 FROM KPIDATA x 
    WHERE x.key LIKE 'k.' + k.id + '.i.' + m.id + '.a.%');