3

I have two tables drivers and drivers_names. What I want is for every driver I select from the first table to have a random name from the second, but what I get is one name for all drivers in the result. Yes, it is different every time but is one for all. Here is my query, I'm using postgresql.

SELECT
    drivers.driver_id AS drivers_driver_id,
    (
        SELECT
            drivers_names.name_en
        FROM
            drivers_names
        ORDER BY random() LIMIT 1
    ) AS driver_name
FROM
    drivers

Result:

11  Denis
13  Denis
7   Denis

Tables structure.

drivers

+--------------+
| column_name  |
+--------------+
| driver_id    |
| property_1   |
| property_2   |
| property_3   |
+--------------+

drivers_names

+-------------+
| column_name |
+-------------+
| name_id     |
| name_en     |
+-------------+
2
  • if you will show structure of both the tables it will be helpful. Commented Aug 1, 2012 at 6:53
  • @HussainNagri I added the structures for both tables. Commented Aug 1, 2012 at 7:07

1 Answer 1

3

Postgres probably evaluates the subselect only once because technically there's no reason to evaluate it for every row. You could force it by referencing a column from the drivers table into the subselect, like this:

SELECT
    drivers.driver_id AS drivers_driver_id,
    (
        SELECT
            drivers_names.name_en
        FROM
            drivers_names
        ORDER BY random()+drivers.driver_id LIMIT 1
    ) AS driver_name
FROM
    drivers
Sign up to request clarification or add additional context in comments.

1 Comment

you can also put random()+drivers.oid::integer which may be a more general solution to all cases (my id was alphanumeric)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.