I am basically having the exact same problem as here:
SQL View: Join tables without causing the data to duplicate on every row?
Except on that question he was using SQL, and I am using mysql. I am wondering if the same query is possible in mysql. If so, I may have the wrong syntax?
I am trying to do something like
select a.name as account_Name,
p.description as property_DESCRIPTION,
p.address as property_ADDRESS,
null as vehicles_DESCRIPTION,
null as vehicles_MAKE,
null as vehicles_MODEL
from Accounts a
inner join Properties p
on a.accountid = p.accountid
UNION ALL
select a.name as account_Name,
null as property_DESCRIPTION,
null as property_ADDRESS,
v.description as vehicles_DESCRIPTION,
v.make as vehicles_MAKE,
v.model as vehicles_MODEL
from Accounts a
inner join vehicles v
on a.accountid = v.accountid
Here is my actual code:
SELECT user.first_name, user.last_name, upi.image_id, NULL AS friends.friend_user_id FROM user
INNER JOIN user_profile_images as upi ON (user.user_id = upi.user_id)
UNION
SELECT user.first_name, user.last_name, NULL AS upi.image_id, friends.friend_user_id FROM user
INNER JOIN friends ON (user.user_id = friends.user_id)
WHERE user.user_id = '$profile_id'
where I have 3 tables: user, user_profile_images, and friends. Both user_profile_images and friends are related to the user through the user_id. So a user can have multiple profile images as well as multiple friend entries. I can post the table diagrams if it doesnt make sense. But what I want is basically a view of all the info, with fields NULL if they don’t apply to the overall view.
If I do the query with 2 tables, either with user and user_profile_images, or user and friends, I get the desired results, but adding the third table gives me duplicate rows.
The solution, as @MarcB suggests, is to use
UNIONrather thanUNION ALL.However, I have a question for you – why use the
UNIONat all? The following is equivalent, except that if (say) account 1 has one property and one vehicle, instead of getting:You’ll get
Query:
Note – the last line (IS NOT NULL for both p and v) simulates the ‘accounts table’ part of the
INNER JOINand makes sure that only accounts with at least a property OR a vehicle are shown. Substitute theidcolumns ofpandvthere.