[英]Help with complex join conditions
我有以下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'
例如,该查询返回一行,其中“强度”为2。理想情况下,我可以为Neurons.id保留一列,为Neurons.name保留一列,为SUM(synapses.strength)保留一列,为每个不同的神经元保留一条记录。
这是您想要的吗?
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
采用:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.