Forum Moderators: coopster
$fields = mysql_query('SELECT ItemID FROM Table1 UNION SELECT ItemID FROM Table2 ORDER BY RAND() LIMIT 1');
There's more criteria than that, but this illustrates the basics of the situation. Essentially I want to randomly select one row from either of the two tables. I've got that part down; the query is returning the results I need.
However, the problem I'm having is finding out which table the query pulled the result from. I'm querying two tables and will return one result - but I need to know which table the result came from. Is there any way to assign it to a variable? If so, how can it be done?
Thanks a lot for any help,
Matthew
SELECT 'Table1' AS TableName, ItemID FROM Table1 UNION SELECT 'Table2' AS TableName, ItemID FROM Table2 ORDER BY RAND() LIMIT 1
A more laborious option is to inspect
ItemID with mysql_fetch_field [php.net]. I'd be curious to hear what is returned in the table slot for a union query.
(SELECT 'Table1' AS TableName, ItemID FROM Table1)
UNION
(SELECT 'Table2' AS TableName, ItemID FROM Table2)
ORDER BY RAND() LIMIT 1;
I'd be curious to hear what is returned in the table slot for a union query.
I ran a quick test. Nothing.
--Without digging in any further (I'm tired ;) ), I would guess that this is because MySQL is probably using a temporary table to store the result set of the UNION query. I could be way off base, but it seems logical.
--Information for column TableName:
--
blob: 0
max_length: 6
multiple_key: 0
name: TableName
not_null: 1
numeric: 0
primary_key: 0
table:
type: string
unique_key: 0
unsigned: 0
zerofill: 0
--
-- Information for column ItemID:
--
blob: 0
max_length: 10
multiple_key: 0
name: ItemID
not_null: 0
numeric: 0
primary_key: 0
table:
type: string
unique_key: 0
unsigned: 0
zerofill: 0
* This would come up for a SELECT COALESCE(Table1.foo,Table2.bar) or other conditional query as well.