Question

I've searched around the internet for a day and nothing seems to be working/helping me.

I have a table that has a list of users and their ids and another table that represents users banning another user. I am inserting the user ids into the bans table instead of their names because I want to normalize my database.

My user table looks like this:

CREATE TABLE IF NOT EXISTS `ids` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  `name` VARCHAR(32) NOT NULL
) ENGINE = INNODB;

And my bans table looks like this:

CREATE TABLE IF NOT EXISTS `bans` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  `banner_id` INT UNSIGNED,
  `banned_id` INT UNSIGNED NOT NULL,
  `reason` VARCHAR(256) DEFAULT NULL
) ENGINE = INNODB;

I want to do a select all for my bans table, but have it be easily readable. Ideally it would look something like:

+-------------+-------------+-----------+
| banner_name | banned_name | reason    |
+-------------+-------------+-----------+
| person A    | person B    | being bad |
...

But I am unable to achieve this result. I can only get 2/3rds of the result with this:

SELECT ids.name AS banner_name, bans.reason 
FROM bans LEFT JOIN (ids) ON (bans.banner_id = ids.id);

However, adding that other name column has proven tricky for me. This looks like a similar question, but when trying to follow the example I get something along the lines of

ERROR 1054 (42S22): Unknown column 'ids.name' in 'field list'

or some other syntax error.

Thank you for reading!

Était-ce utile?

La solution

Read about aliasies.

You can include the same table multiple times addin aliases

For example

FROM bans b 
  JOIN ids as i1 ON b.banner_id = i1.id
  JOIN ids as i2 ON b.banned_id= i2.id
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top