2013-04-10 30 views
0

是否有有效的算法來確定項目配置文件並選擇與查詢匹配的配置文件?Mysql剖析項目並選擇匹配的配置文件

例如

TABLE MEN 
id name 
1 man1 
2 man2 
3 man3 


TABLE PROPERTIES 
id name 
1 health_points 
2 strenght 
3 speed 


TABLE MEN_PROPERTIES 
id man_id property_id property_counter 
1 1  1   1000 
2 1  2   100 
3 1  3   50 
4 2  1   100 
5 2  2   200 
6 2  3   100 
7 3  1   100 
8 3  2   10 
9 3  3   5 

這意味着

man1 { 
    health_point:1000, 
    strenght:100 
    speed:50 
} 

man2 { 
    health_point:100, 
    strenght:200 
    speed:100 
} 

man3 { 
    health_point:100, 
    strenght:10 
    speed:5 
} 

比方說,我在man_1工作,我們直觀地瞭解它的輪廓與man_3輪廓相匹配。我希望mysql將man_3作爲與man_1配置文件匹配的配置文件返回。

達到結果的最佳方法是什麼?

+2

爲什麼man_3與man_1相匹配? – 2013-04-10 12:40:54

+0

好吧,它與man_1平衡,但價值較低,我在尋找比例匹配 – Mike 2013-04-10 12:42:22

+0

是的,如果man3 {health_point:100,strenght:20,speed:5}和man4 {health_point:100,實力:10,速度:5 }他們都匹配,但man_4是最接近的 – Mike 2013-04-10 12:45:07

回答

1
SELECT x.* 
FROM  
     (
      SELECT a.ID, 
        a.Name, 
        MAX(IF(c.Name = 'health_points', b.property_counter, NULL)) health_points, 
        MAX(IF(c.Name = 'strenght', b.property_counter, NULL)) strenght, 
        MAX(IF(c.Name = 'speed', b.property_counter, NULL)) speed 
      FROM Men a 
        INNER JOIN Men_Properties b 
         ON a.ID = b.man_ID 
        INNER JOIN Properties c 
         ON b.Property_ID = c.ID 
      WHERE a.ID <> 1 
      GROUP BY a.ID, a.Name 
     ) x 
     CROSS JOIN 
     (
      SELECT a.ID, 
        a.Name, 
        MAX(IF(c.Name = 'health_points', b.property_counter, NULL)) health_points, 
        MAX(IF(c.Name = 'strenght', b.property_counter, NULL)) strenght, 
        MAX(IF(c.Name = 'speed', b.property_counter, NULL)) speed 
      FROM Men a 
        INNER JOIN Men_Properties b 
         ON a.ID = b.man_ID 
        INNER JOIN Properties c 
         ON b.Property_ID = c.ID 
      WHERE a.ID = 1 
      GROUP BY a.ID, a.Name 
     ) y 
WHERE (x.health_points * 1.0/y.health_points) = (x.strenght * 1.0/y.strenght) AND 
     (x.strenght * 1.0/y.strenght) = (x.speed * 1.0/y.speed) 
+0

好吧,現在我需要深入瞭解它!我會盡快遣散:) – Mike 2013-04-10 13:18:07

+0

查詢所做的是靜態地在子查詢中旋轉表格並篩選特定ID。子查詢的結果然後在所有記錄上交叉引用。 – 2013-04-10 13:20:38