This is not working because r937 was probably in a hurry and made a mistake, the COALESCE comparison should be != (not =). Try this:
Code:
(SELECT member_id
, name
, birth_date
, email
, 1 AS pos
FROM members)
UNION ALL
(SELECT member_id
, spouse_name
, spouse_birth_date
, spouse_email
, 2 AS pos
FROM members
WHERE COALESCE(spouse_name,'') != '')
ORDER
BY member_id, pos
Moreover, I added the field 'pos' in the result sets so that you can have consistent sorting - that is member data first, spouse data second.
UNION simply joins two separate queries and returns results of both in a single result set - instead of running 2 separate queries and then merging the results in another language (like php) you are doing it all in sql.
COALESCE(spouse_name,'') != '' means that the result should be returned only if spouse_name is defined (if it's other than NULL or empty string). In fact when no spouse data is present you should have NULL values in the table, then change WHERE COALESCE(spouse_name,'') != '' to:
Code:
WHERE spouse_name IS NOT NULL
because it's shorter and faster.
Bookmarks