1

我有一个我继承的脚本,它可以即时生成 SQL,然后针对 mySQL 数据库执行它。

目前,它的“WHERE”子句仅限于简单的 WHERE AND AND AND AND 语句

例如

SELECT * FROM Trucks WHERE Make = 'Volvo' AND Dealership = 'United' AND color ='White'  

在最坏的情况下,它可以串接这些 AND 子句中的 40 个

对我来说,附加 AND 参数非常简单。不得不重写它会很痛苦。

我的问题是:我需要在相关表上进行搜索。我需要找出一种方法来维护 AND AND AND,但我可以在 AND 中使用我想要的尽可能复杂的参数。

所以我的代码看起来像

SELECT * FROM Trucks WHERE Make = 'Volvo' AND (anything mySQL likes) AND color ='White'

这是架构:

CREATE  TABLE `Trucks` (
  `ID` INT NOT NULL AUTO_INCREMENT ,
  `Make` VARCHAR(45) NULL ,
  `Current_PartList_ID` INT NULL ,
  PRIMARY KEY (`ID`) );

INSERT INTO `Trucks` (`Make`, `Current_PartList_ID`) VALUES ('Volvo', '1');
INSERT INTO `Trucks` (`Make`, `Current_PartList_ID`) VALUES ('Volvo', '2');
INSERT INTO `Trucks` (`Make`, `Current_PartList_ID`) VALUES ('Mac', '3');
INSERT INTO `Trucks` (`Make`, `Current_PartList_ID`) VALUES ('Mac', '5');
INSERT INTO `Trucks` (`Make`, `Current_PartList_ID`) VALUES ('Daihatsu', '8');
INSERT INTO `Trucks` (`Make`, `Current_PartList_ID`) VALUES ('Volvo', '4');


CREATE  TABLE `Parts_lists` (
  `ID` INT NOT NULL AUTO_INCREMENT ,
  `Carb_Model` VARCHAR(45) NULL ,
  `Carb_date` DATE NULL ,
  `Tire_type` VARCHAR(45) NULL ,
  `Tire_date` DATE NULL ,
  PRIMARY KEY (`ID`) );

INSERT INTO `Parts_lists` (`Carb_Model`, `Carb_date`, `Tire_type`, `Tire_date`) VALUES ('Hirsch', '2012-12-19', 'Toyo', '2013-01-01');
INSERT INTO `Parts_lists` (`Carb_Model`, `Carb_date`, `Tire_type`, `Tire_date`) VALUES ('HIrsch', '2013-02-14', 'Goodyear', '2011-03-16');
INSERT INTO `Parts_lists` (`Carb_Model`, `Carb_date`, `Tire_type`, `Tire_date`) VALUES ('Bosch', '2011-11-04', 'Toyo', '2013-01-01');
INSERT INTO `Parts_lists` (`Carb_Model`, `Carb_date`, `Tire_type`, `Tire_date`) VALUES ('Miller', '2009-10-11', 'Toyo', '2010-04-17');
INSERT INTO `Parts_lists` (`Carb_Model`, `Carb_date`, `Tire_type`, `Tire_date`) VALUES ('Bosch', '2011-01-07', 'Goodyear', '2013-01-06');
INSERT INTO `Parts_lists` (`Carb_Model`, `Carb_date`, `Tire_type`, `Tire_date`) VALUES ('Bosch', '2012-09-16', 'Lamb', '2012-06-25');
INSERT INTO `Parts_lists` (`Carb_Model`, `Carb_date`, `Tire_type`, `Tire_date`) VALUES ('Miller', '2011-07-22', 'Unknown', '2012-04-07');
INSERT INTO `Parts_lists` (`Carb_Model`, `Carb_date`, `Tire_type`, `Tire_date`) VALUES ('Davis', '2009-03-09', 'Hawking', '2012-06-16');
INSERT INTO `Parts_lists` (`Carb_Model`, `Carb_date`, `Tire_type`, `Tire_date`) VALUES ('Sanno', '2010-01-07', 'Goodyear', '2009-07-16');
INSERT INTO `Parts_lists` (`Carb_Model`, `Carb_date`, `Tire_type`, `Tire_date`) VALUES ('Thrust', '2012-11-11', 'Lamb', '2004-04-08');

牢记这个 AND 结构。我将如何获得:所有配备 Hirsch Carbs 的沃尔沃卡车?

(在这种情况下是卡车表中的记录 1 和 2)

4

1 回答 1

2

尝试:

SELECT * FROM Trucks WHERE Make = 'Volvo' AND Current_PartList_ID in (select ID from    Parts_List where Carb_Model = 'Hirsch')
于 2013-05-22T04:35:24.957 回答