Note that there are some explanatory texts on larger screens.

plurals
  1. PORandom record from maximum set (with an additional constraint)
    primarykey
    data
    text
    <p>Two tables, products and producers. I would like to buy a particular type of product, but only from the highest priority producer that makes it, and I need their URL. If multiple producers have the highest priority, then give each producer and equal chance of being selected.</p> <p>I decide to buy a car for example. From the sample data below, Honda and Ford are the cars with the the highest priority, so return a Honda URL 50% of the time and the Ford URL 50%.</p> <pre><code>Products Table: | producer_id | product_type | product_url | |-------------|--------------|-----------------| | 3 | car | wiki.com/a.html | | 1 | bat | wiki.com/b.html | | 2 | car | wiki.com/c.html | | 4 | car | wiki.com/d.html | | 2 | car | wiki.com/e.html | Producers Table:| producer_id | producer | priority | |-------------|----------|----------| | 1 | wilson | 30 | | 2 | honda | 20 | | 3 | mazda | 5 | | 4 | ford | 20 | </code></pre> <p>The mess I have at the moment I'm sure can be simplified:</p> <pre><code>SELECT products.url FROM products, producers WHERE products.producer_id = producers.producer_id AND products.product_type = 'car' AND priority IN (SELECT MAX(priority) FROM products, providers WHERE products.producer_id = producers.producer_id AND products.product_type = 'car' ) ORDER BY RAND() LIMIT 1 </code></pre> <p>plus it has the problem where it will return Honda's pages 2/3rds of the time because Honda has two models of the three with highest priority. </p> <p>Looking forward to learning something!</p>
    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.
    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