Skip to content
Advertisement

Query SQL values with possible empty records

I have 4 tables that I want to run a single query on. I want specific values from each table that all relate to a single user.

However, some of these tables may not have any associated records. If there are no records in a given table, the query set comes back as empty (because there are no records pertaining to the specified user in the table).

Question

How do we pull all values for a user and insert blanks/null in the columns that have no values?

My query:

SELECT PLAYER.UUID,
       XP,
       RANKS.RANKNAME,
       HORSE.HEALTH_LEVEL,
       HORSE.SPEED_LEVEL,
       HORSE.JUMP_LEVEL,
       special_weapons.name
FROM PLAYER,
     HORSE,
     RANKS,
     Special_weapons
WHERE PLAYER.UUID = HORSE.UUID
  AND PLAYER.RANKID = RANKS.RANKID
  AND PLAYER.UUID = 'sldjnofw-adfdafd-113rsada'
  AND Player.uuid = special_weapons.uuid;

My table structure:

enter image description here

My table contents:

enter image description here

The special weapons table in this case is empty. Blanks should populate missing columns in the above query. Instead, an empty set is returned.

Advertisement

Answer

You need LEFT JOIN in such cases. Try below

SELECT player.uuid
      ,xp
      ,ranks.rankname
      ,horse.health_level
      ,horse.speed_level
      ,horse.jump_level
      ,special_weapons.name
FROM   player
LEFT   JOIN horse
ON     player.uuid = horse.uuid
LEFT   JOIN ranks
ON     player.rankid = ranks.rankid
LEFT   JOIN special_weapons
ON     player.uuid = special_weapons.uuid
WHERE  player.uuid = 'sldjnofw-adfdafd-113rsada';
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement