0

我是 javascript 和 nodejs 的初学者,对 mysql 了解不多。这些是我的 MySQL 表的列名,其名称为cars

  • 姓名
  • 模型
  • 传输类型
  • 发动机尺寸
  • 车辆尺寸
  • 体型

我想随机选择Namemodelfrom cars,但类别必须匹配,这将由其他四个列决定:TransmissionType,和EngineSize,以这样一种方式随机选择的汽车必须共享相同的值,和。输出应该只有两行。VehicleSizeBody TypeengineTransmissionTypeVehicheSizeBodyType

发动机尺寸具有以下值:3.2, 3.5, 1.6, 5.2, 2.0, 2.2

传输类型具有值:ManualAutomatic

VehicleSize 具有值CompactMidSizeLarge

BodyType 具有值Carvantruck

我应该写什么查询来实现这一点?请帮忙。

我这样做了,查询工作正常,但是其中运行的子查询太多,是否可以使用不更多的 den 2-3 子查询来实现这一点?

SELECT Name, model 
FROM cars 
WHERE EngineSize IN (SELECT * FROM (SELECT EngineSize FROM cars  ORDER BY RAND( ) LIMIT 1 ) AS A)  
AND TransmissionType IN (SELECT * FROM (SELECT TransmissionType  FROM cars ORDER BY RAND( ) LIMIT 1 ) AS B)
AND BodyType IN (SELECT * FROM (SELECT BodyType  FROM cars ORDER BY RAND( ) LIMIT 1 ) AS C)   
AND VehicleSize IN (SELECT * FROM (SELECT VehicleSize` FROM cars ORDER BY RAND( ) LIMIT 1 ) AS D)    
LIMIT 2
4

2 回答 2

1

如果您正在搜索与某些类别匹配的车辆列表,您可以这样做;

SELECT Name, model, Id * RAND() AS random_no
FROM   cars
WHERE  EngineSize = '2.2'
AND    TransmissionType = 'Automatic'
AND    VehicleSize = 'Large'
AND    BodyType = 'Car'
ORDER by random_no
LIMIT 1

如果你是动态的,你应该通过你的 javascript 中的参数传递值(在上面的例子中是硬编码的)。

于 2013-10-08T09:45:08.980 回答
0
SELECT Name, model
FROM   cars
WHERE  EngineSize = '2.2'
AND    TransmissionType = 'Automatic'
AND    VehicleSize = 'Large'
AND    BodyType = 'Car'
ORDER by RAND()
LIMIT 2

此选择将选择符合 where 子句的所有结果,以随机方式重新排序结果,然后将返回限制为符合条件的前 2 个。有关更多详细信息,请参阅此博客、这些说明和此SO 帖子

于 2013-10-08T13:08:29.910 回答