在多个表中排序仅在mySQL中使用AND

时间:2013-05-22 04:26:56

标签: mysql

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

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

例如

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

在最坏的情况下,它可以串起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?

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

1 个答案:

答案 0 :(得分:2)

尝试:

SELECT * FROM Trucks WHERE Make = 'Volvo' AND Current_PartList_ID in (select ID from    Parts_List where Carb_Model = 'Hirsch')