work
work

Reputation:

Using UNION in a query with PHP

I have an SQL query which links 3 tables using UNION:

$sql ="(SELECT Drive.DriveID,Ram.Memory from Drive,Ram where Drive.DriveID = Ram.RamID) UNION
(SELECT Drive.DriveID,External.Memory from Drive, External where Drive.DriveID = External.ExtID)";

Suppose I want to get Ram.Name as well. How do I do this? If I use Ram.Name in the first SELECT statement it would not produce the correct result.

Any method for tackling this? I want to do it using UNION.

Upvotes: 0

Views: 194

Answers (1)

Charles Graham
Charles Graham

Reputation: 1157

In a Union query, all of the columns must be specified in all of the statements in the same order.

Therefore you'd need to have

(SELECT Drive.DriveID,Ram.Memory,Ram.Name
 from Drive,Ram
 where Drive.DriveID = Ram.RamID)
UNION
(SELECT Drive.DriveID,External.Memory, '' as Name
 from Drive, External
 where Drive.DriveID = External.ExtID)

Or if your External table has a Name field you could Include that one instead of an empty string.

Upvotes: 5

Related Questions