mysql - How to display primary key from junctional table in result table after JOIN query?

24 Views Asked by At

I have a relational database model. Because I am learning MySQL queries for this kind of database design, I know the basics, but I got to the problem.

These are my tables:

 hgs_word_types           hgs_meanings
 +----+-----------+       +----+-----------+
 | id | word_type |       | id | meaning   |
 +----+-----------+       +----+-----------+
 | 1  | noun      |       | 1  | man       |
 +----+-----------+       +----+-----------+

 junc_meaning_word_type
 +----+------------+--------------+
 | id | meaning_id | word_type_id |
 +----+------------+--------------+
 | 1  | 1          | 1            |
 +----+------------+--------------+ 

This is my query:

SELECT hgs_word_types.word_type, hgs_meanings.meaning
FROM junc_meaning_word_type
JOIN hgs_word_types ON junc_meaning_word_type.word_type_id = hgs_word_types.id
JOIN hgs_meanings ON junc_meaning_word_type.meaning_id = hgs_meanings.id

I am getting the result like this:

+---------------------+
| meaning | word_type |
+---------+-----------+
| man     | noun      |
+---------+-----------+

How to show junc_meaning_word_type.id in the result of this query as a 3rd column? How to make something like this:

+----+---------------------+
| id | meaning | word_type |
+----+---------+-----------+
| 1  | man     | noun      |
+----+---------+-----------+

Every help is appreciated.

1

There are 1 best solutions below

1
On BEST ANSWER

You can simply select the required column(s). In this case, you need to add junc_meaning_word_type.id to the SELECT clause as well.

Also, it is advisable to use Aliasing in case of multi-table queries, for code clarity (readability) and avoiding ambiguous behaviour.

SELECT junc.id, 
       typ.word_type, 
       mean.meaning
FROM junc_meaning_word_type AS junc
JOIN hgs_word_types AS typ
  ON junc.word_type_id = typ.id
JOIN hgs_meanings AS mean 
  ON junc.meaning_id = mean.id