帮助处理复杂的连接条件

时间:2010-09-16 16:05:27

标签: sql mysql database-design join

我有以下mysql表架构:

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";

--
-- Database: `network`
--

-- --------------------------------------------------------

--
-- Table structure for table `contexts`
--

CREATE TABLE IF NOT EXISTS `contexts` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `keyword` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;

-- --------------------------------------------------------

--
-- Table structure for table `neurons`
--

CREATE TABLE IF NOT EXISTS `neurons` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

-- --------------------------------------------------------

--
-- Table structure for table `synapses`
--

CREATE TABLE IF NOT EXISTS `synapses` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `n1_id` int(11) NOT NULL,
  `n2_id` int(11) NOT NULL,
  `context_id` int(11) NOT NULL,
  `strength` double NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;

我可以编写哪些SQL来获取与指定上下文关联的所有神经元以及与每个神经元相关的突触的强度列的总和?

我正在使用以下查询,该查询返回与一个神经元相关联的突触强度的总和。我需要获取所有神经元的信息:

/* This query finds how strongly the neuron with id 1 is connected to the context with keyword ice cream*/

SELECT SUM(strength) AS Strength FROM
synapses
JOIN contexts AS Context ON synapses.context_id = Context.id
JOIN neurons AS Neuron ON Neuron.id = synapses.n1_id OR Neuron.id = synapses.n2_id
WHERE Neuron.id = 1 AND Context.keyword = 'ice cream'

例如,该查询返回一行,其中Strength为2.理想情况下,我可以有一列用于neurons.id,一列用于neurons.name,一列用于SUM(synapses.strength),每列一列独特的神经元。

2 个答案:

答案 0 :(得分:1)

这样做你想要的吗?

SELECT contexts.keyword, neurons.id, neurons.name, SUM(synapses.strength)
FROM neurons
INNER JOIN synapses ON neurons.id = synapses.n1_id OR neurons.id = synapses.n2_id
INNER JOIN contexts ON synapses.context_id = contexts.id
GROUP BY contexts.keyword, neurons.id, neurons.name

答案 1 :(得分:1)

使用:

   SELECT DISTINCT 
          n.*,
          COALESCE(x.strength, 0) AS strength
     FROM NEURONS n
     JOIN SYNAPSES s ON n.id IN (s.n1_id, s.n2_id)
     JOIN CONTEXTS c ON c.id = s.context_id
LEFT JOIN (SELECT c.id AS c_id,
                  n.id AS n_id,
                  SUM(strength) AS Strength 
             FROM SYNAPSES s
             JOIN CONTEXTS c ON c.id = s.context_id
             JOIN NEURONS n ON n.id IN (s.n1_id, s.n2_id)
         GROUP BY c.id, n.id) x ON x.c_id = c.id
                               AND x.n_id = n.id