0

I am beginner in javascript and nodejs, and not having much knowledge of mysql. These are the column names of my MySQL table whose name is cars:

  • Name
  • model
  • TransmissionType
  • EngineSize
  • VehicleSize
  • BodyType

I want to randomly select Name and model from cars, but the category must match which will be decided by the other four coloumns: TransmissionType, EngineSize, VehicleSize and Body Type, in such a way that randomly selected cars must share same values for engine, TransmissionType, VehicheSize and BodyType. Output should be in two rows only.

Engine size has values: 3.2, 3.5, 1.6, 5.2, 2.0, 2.2

TransmissionType has values: Manual and Automatic

VehicleSize has values: Compact, MidSize and Large.

BodyType has values: Car, van and truck.

What query should I write to achieve this? Please help.

I did this, and the query is working fine, but there are too many sub-queries are running in it, is it possible to achieve this using not more den 2-3 sub-queries?

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
Akshat
  • 479
  • 4
  • 9

2 Answers2

1

If you are in search of a list of vehicles matching certain categories, you can do this;

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

And if you're doing it dynamically, you should pass the values (hardcoded in the above example) by parameters from your javascript.

Nadeem_MK
  • 7,533
  • 7
  • 50
  • 61
0
SELECT Name, model
FROM   cars
WHERE  EngineSize = '2.2'
AND    TransmissionType = 'Automatic'
AND    VehicleSize = 'Large'
AND    BodyType = 'Car'
ORDER by RAND()
LIMIT 2

This select will select all results fitting the where clause, reorder the results in a random way, then limit the return to the first 2 fitting the criteria. See this blog, these instructions, and this SO post for more details.

Community
  • 1
  • 1
cs_alumnus
  • 1,579
  • 16
  • 24