从WHERE子句中选择所有行MINUS行

时间:2015-08-07 08:55:49

标签: mysql

我如何修改查询以便从表中获取除查询中使用的所有行之外的所有行?

SELECT * 
FROM cars 
WHERE (makeModelDescription='Seat Arosa 2.0 Stella' 
         AND firstRegistration='EZ 03/2005' 
         AND mileage='101.000 km') 
      OR (makeModelDescription='Seat Arosa 3.0 Stella' 
             AND firstRegistration='EZ 03/2005' 
             AND mileage='101.000 km')

请注意,在条件中使用所有三个属性makeModelDescription,firstRegistration和mileage作为关键是很重要的。

参考表:

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";

--
-- Datenbank: `ref-table`
--

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

--
-- Tabellenstruktur für Tabelle `cars`
--

CREATE TABLE `cars` (
  `makeModelDescription` varchar(150) COLLATE utf8_unicode_ci NOT NULL,
  `firstRegistration` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
  `mileage` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
  `status` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
  `createTime` int(11) NOT NULL,
  `updateTime` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Daten für Tabelle `cars`
--

INSERT INTO `cars` (`makeModelDescription`, `firstRegistration`, `mileage`, `status`, `createTime`, `updateTime`) VALUES
('BMW X5 4.4 i  aus erster Hand', 'EZ 07/2000', '226.000 km', 'active', 1438870958, 1438870958),
('Corvette C5 Cabrio', 'EZ 03/2001', '96.000 km', 'active', 1438870958, 1438870958),
('Seat Arosa 2.0 Stella', 'EZ 03/2005', '101.000 km', 'active', 1436891529, 1436891529),
('Seat Arosa 2.0 Stella', 'EZ 03/2006', '101.000 km', 'active', 1436891529, 1436891529),
('Seat Arosa 3.0 Stella', 'EZ 03/2005', '101.000 km', 'active', 1437029730, 1437029730),
('Seat Arosa 4.0 Stella', 'EZ 03/2005', '101.000 km', 'active', 1437112074, 1437112074);

--
-- Indizes der exportierten Tabellen
--

--
-- Indizes für die Tabelle `cars`
--
ALTER TABLE `cars`
 ADD PRIMARY KEY (`makeModelDescription`,`firstRegistration`,`mileage`);

过去通过自己获取查询这是一项简单的任务,但实际上并非如此。我也尝试过不同的提议解决方案,但现在没有一个解决方案能够提供所需的结果。

2 个答案:

答案 0 :(得分:2)

由于所有列都不可为空,您只需使用NOT来获取那些与条件不匹配的记录:

SELECT * 
FROM cars 
WHERE NOT
(
  (makeModelDescription='Seat Arosa 2.0 Stella' 
   AND firstRegistration='EZ 03/2005' 
   AND mileage='101.000 km') 
  OR 
  (makeModelDescription='Seat Arosa 3.0 Stella' 
   AND firstRegistration='EZ 03/2005' 
   AND mileage='101.000 km')
);

答案 1 :(得分:0)

请参阅http://sqlfiddle.com/#!9/1765e/1/0

SELECT * 
FROM cars 
WHERE NOT ((makeModelDescription='Seat Arosa 2.0 Stella' 
         AND firstRegistration='EZ 03/2005' 
         AND mileage='101.000 km') 
      OR (makeModelDescription='Seat Arosa 3.0 Stella' 
             AND firstRegistration='EZ 03/2005' 
             AND mileage='101.000 km'))