获取列中名称的顺序

时间:2015-06-29 09:10:23

标签: mysql

stop_name表中DEF未增加的ABC, DEF, GHI表中存在stop_name的以下顺序behaviour时,我试图获取behaviour_id 1 Tree 3 Tree 5 ABC 8 ABC 9 DEF 11 DEF 13 DEF 17 GHI 21 Moon 一个和名称在表中存在多次,它也不总是存在一次。如何使用mysql查询获取它?

简单:

CREATE TABLE IF NOT EXISTS behaviour(
    behaviour_id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
    mac VARCHAR(30) NOT NULL,
    stop_name VARCHAR(30) NOT NULL,    
    stop_distance INT(11) NOT NULL, 
    speed INT(11) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)

表格

SELECT
    b3.behaviour_id
FROM
    behaviour b1
    INNER JOIN behaviour b2 ON b1.behaviour_id = b2.behaviour_id - 1
    INNER JOIN behaviour b3 ON b2.behaviour_id = b3.behaviour_id - 1
WHERE
    CONCAT(b1.stop_name, b2.stop_name, b3.stop_name) = CONCAT('ABC', 'DEF', 'GHI')
    AND b1.mac = '12:EF:34:DF:89:JH';

当id增加一个

时,此查询有效
 public class A {

@Override
        public int hashCode(){
        System.out.println("hashcode");
        return 1;
        }
        public static void main(String... s){
        HashMap<A,String> hm = new HashMap<A,String>();
        A A1 = new A();
        A A2 = A1;
        A A3 =new A();
        hm.put(A2,"sometext");
        hm.put(A3,"sometext2");
        System.out.println(hm);
        }



}

1 个答案:

答案 0 :(得分:1)

这样的东西
select b1.id i1,b2.id i2,b3.id i3 FROM behav b1 
INNER JOIN behav b2 ON b2.name='DEF' AND b2.id>b1.id
INNER JOIN behav b3 ON b3.name='GHI' AND b3.id>b2.id
WHERE b1.name='ABC'

应该起作用并给出以下结果:

i1  i2  i3
5   9   17
8   9   17
5   11  17
8   11  17
5   13  17
8   13  17

当然,如果您只想要第一次出现,请执行

select b1.id i1,b2.id i2,b3.id i3 FROM behav b1 
INNER JOIN behav b2 ON b2.name='DEF' AND b2.id>b1.id
INNER JOIN behav b3 ON b3.name='GHI' AND b3.id>b2.id
WHERE b1.name='ABC' ORDER BY i1,i2 LIMIT 1