有点高级MySQL查询(至少对我来说)

时间:2018-03-30 07:33:13

标签: mysql sql

我的部分数据库:

enter image description here

一个设备可以触发多个动作,不同设备可以触发相同的动作,因此联结表

我想选择属于群组的所有设备 &他们被链接到的动作(如果它们恰好是)

我已经非常接近使用2个查询一个接一个。问题是,每台设备不会返回多个动作。我笨重的解决方法也完全区分了无动作设备和那些触发动作的设备。

SELECT 
    d.sigfox_id, type 
FROM 
    groups g, devices d, triggers t, actions a 
WHERE 
    t.action_id = a.action_id 
    AND t.sigfox_id = d.sigfox_id 
    AND d.group_id = g.group_id 
    AND g.name = ? 
GROUP BY 
    t.sigfox_id


SELECT 
    action_id, type 
FROM  
    actions 
WHERE 
    group_id = ?

3 个答案:

答案 0 :(得分:1)

enter image description here

大!你可以了解加入!

SELECT 
d.sigfox_id, d.type
action_id
FROM groups g
    LEFT OUTER JOIN actions a ON d.type = g.type
WHERE t.action_id = a.action_id 
AND t.sigfox_id = d.sigfox_id 
AND d.group_id = g.group_id 
AND g.name = ? 
GROUP BY t.sigfox_id

答案 1 :(得分:1)

查看您的架构,您应该使用一组内部联接和一个区别子句来避免重复的重写

  select distinct a.action_id, a.type 
  from group g 
  inner join  devices d on g.group_id = d.g.group_id  and g.name = ?
  inner join  triggers t on t.sigfox_id = d.sigfox_id 
  inner join actions a on a.action_id = t.action_id

答案 2 :(得分:0)

当您使用sigfox_id进行分组时,它将提供不同的sigfox_id。

执行不带GROUP BY t.sigfox_id

的查询
SELECT d.sigfox_id, type FROM groups g, devices d, triggers t, actions 
WHERE t.action_id = a.action_id 
AND t.sigfox_id = d.sigfox_id 
AND d.group_id = g.group_id 
AND g.name = ?