我有以下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),每個不同神經元具有一個記錄。
這個查詢是更快。我試着用一個添加的WHERE context.keyword LIKE'%ice%'... Mike的SQL花了0.0218秒。小馬的代碼花了0.0007秒。爲什麼這個查詢要快得多? – Adam 2010-09-16 16:23:38
@Adam:可能與不同的語法有關(換出或換一個IN子句)。另外,對於總和而言,組合的標準更少。 – 2010-09-16 16:27:28