SQL查询根据同一字段中的2个不同值和条件选择记录
我为印度铁路项目创建了一个这样的表:
CREATE TABLE IF NOT EXISTS `dennis` (
`trid` varchar(50) NOT NULL,
`place` varchar(50) NOT NULL,
`si` varchar(50) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
然后我以这种方式插入行:
INSERT INTO `dennis` (`trid`, `place`, `si`) VALUES
('100', 'cochi', '3'),
('300', 'cochi', '1'),
('100', 'mumbai', '1'),
('100', 'bangalore', '2'),
('300', 'bangalore', '2'),
('300', 'mumbai', '3'),
('200', 'hyderabad', '1'),
('400', 'trivandrum', '1'),
('200', 'bangalore', '2'),
('200', 'trivandrum', '3'),
('400', 'bangalore', '2'),
('400', 'hyderabad', '3');
我的问题是当我选择起始站为班加罗尔,目的地为孟买时,我得到了所有火车号码,因为班加罗尔存在所有 trid ie trainid 但孟买仅存在 100 和 300。
我需要一个查询,该查询只能返回同时拥有孟买和班加罗尔的 trid。此外,班加罗尔的 si 序列号必须小于孟买的 si。
我使用了这个查询,但它似乎返回了所有记录
SELECT DISTINCT trid FROM dennis WHERE place ='mumbai' OR place='bangalore'
I Created a table like this for indian railways project:
CREATE TABLE IF NOT EXISTS `dennis` (
`trid` varchar(50) NOT NULL,
`place` varchar(50) NOT NULL,
`si` varchar(50) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
then i inserted rows this way :
INSERT INTO `dennis` (`trid`, `place`, `si`) VALUES
('100', 'cochi', '3'),
('300', 'cochi', '1'),
('100', 'mumbai', '1'),
('100', 'bangalore', '2'),
('300', 'bangalore', '2'),
('300', 'mumbai', '3'),
('200', 'hyderabad', '1'),
('400', 'trivandrum', '1'),
('200', 'bangalore', '2'),
('200', 'trivandrum', '3'),
('400', 'bangalore', '2'),
('400', 'hyderabad', '3');
My problem is when i select start station as Bangalore and destination as mumbai, I am getting all the train numbers because bangalore exist for all trid ie trainid but mumbai exist only for 100 and 300.
I need a query that can return only those trid who have both mumbai and bangalore. Also the si ie Serialnumber of bangalore must be lesser than si of mumbai.
i used this query but it seems to return all the record
SELECT DISTINCT trid FROM dennis WHERE place ='mumbai' OR place='bangalore'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
试试这个,
希望这能回答你的问题
try this,
hope this answers your question