我有一个独特的情况。我有一个动态生成 SQl 并针对 mySQL 数据库运行它的函数。它一步一步构建SQL查询,非常复杂。
在 WHERE 子句中最多可以有 40 个不同的 AND。例如。
SELECT * FROM TableX //yea I know don't search for * ... trying to save typing on stack.
WHERE Size = 'Large'
AND color= 'blue'
AND smell = 'stinky'
AND ugly = 'no'
AND brand = 'United'
etc...
最后它会输出一行 ORDER BY。如:
ORDER BY brand
我的挑战是我只能使用 ORDER BY some string进行排序。如果我想从主表中订购数据,这很好用。但是,如果它来自相关表,我该怎么办?
假设我有以下架构:
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');
我想得到:
SELECT * FROM Trucks WHERE Make = 'volvo' ORDER BY (*Parts_List.Carb_date*)
因此给了我以下选择
ID Make (why)
6 Volvo (Because the Carb_date is 2009-10-11)
1 Volvo (Because the Carb_date is 2012-12-19)
2 Volvo (Because the Carb_date is 2013-02-14)
非常清楚:我坚持:以下文本(我根本无法编辑它:没有完全重写一个古老的丑陋应用程序):
SELECT * FROM Trucks WHERE Make = 'volvo' ORDER BY
我需要 XXXXXXX 的字符串
SELECT * FROM Trucks WHERE Make = 'volvo' ORDER BY XXXXXXX