I have three tables, A B and C. For every entry in A x B (where x is a Cartesian product, or cross join) there is an entry in C.
In other words, the table for C might look like this, if there were 2 entries for A and 3 for B:
| A_ID | B_ID | C_Val |
----------------------|
| 1 | 1 | 100 |
| 1 | 2 | 56 |
| 1 | 3 | 19 |
| 2 | 1 | 67 |
| 2 | 2 | 0 |
| 2 | 3 | 99 |
Thus, for any combination of A and B, there’s a value to be looked up in C. I hope this all makes sense.
In practice, the size of A x B may be relatively small for a database, but far too large to populate by hand for testing data. Thus, I would like to randomlly populate C‘s table for whatever data may already be in A and B.
My knowledge of SQL is fairly basic. What I’ve determined I can do so far is get that cartesian product as an inner query, like so:
(SELECT B.B_ID, C.C_ID
FROM B CROSS JOIN C)
Then I want to say something like follows:
INSERT INTO A(B_ID, C_ID, A_Val) VALUES
(SELECT B.B_ID, C.C_ID, FLOOR(RAND() * 100)
FROM B CROSS JOIN C)
Not surprisingly, this doesn’t work. I don’t think its valid syntax to genereate a column on the fly like that, nor to try to insert a whole table as values.
How can I basically convert this normal programming pseudocode to proper SQL?
foreach(A_ID in A){
foreach(B_ID in B){
C.insert(A_ID, B_ID, Rand(100));
}
}
The syntax problem is because:
Should be:
(You don’t use
VALUESwithINSERT/SELECT.)However you will still have the problem that
RAND()is not evaluated for every row; it will have the same value for every row. Assuming the combination of B_ID and C_ID is unique, you can use something like this: