Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to select two random rows with same category in MySQL
    primarykey
    data
    text
    <p>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 <code>cars</code>:</p> <ul> <li>Name</li> <li>model</li> <li>TransmissionType</li> <li>EngineSize</li> <li>VehicleSize</li> <li>BodyType</li> </ul> <p>I want to randomly select <code>Name</code> and <code>model</code> from <code>cars</code>, but the category must match which will be decided by the other four coloumns: <code>TransmissionType</code>, <code>EngineSize</code>, <code>VehicleSize</code> and <code>Body Type</code>, in such a way that randomly selected cars must share same values for <code>engine</code>, <code>TransmissionType</code>, <code>VehicheSize</code> and <code>BodyType</code>. Output should be in two rows only.</p> <p>Engine size has values: <code>3.2, 3.5, 1.6, 5.2, 2.0, 2.2</code></p> <p>TransmissionType has values: <code>Manual</code> and <code>Automatic</code></p> <p>VehicleSize has values: <code>Compact</code>, <code>MidSize</code> and <code>Large</code>.</p> <p>BodyType has values: <code>Car</code>, <code>van</code> and <code>truck</code>.</p> <p>What query should I write to achieve this? Please help. </p> <p>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? </p> <pre><code>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 </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload