简体   繁体   中英

MySQL query with Foreign Key

I have the following tables related as shown below.

~~~~articles~~~~~~      ~~~~categories~~~~         ~~~user_categ~~~    ~~users~~~
|  id_articles    |      |  c_id          |       |   user_cat_id  |  _|_user_id |
|  article_title  |     _|_ category_id   |_____  |   user_id_fk   |_/ |user_name|
|  article_content| _ -  |  category_name |     \_|__category_id_fk|   |user_pw  |
|  category_id    |/     |________________|       |________________|   |_________| 
|_________________|

Now in my user_categories table let's say I have the following data.

| user_id_fk | cat_id_fk |
-------------------------
| 2          | 2.1       |
| 2          | 3.1       |
| 2          | 4.1       |
| 3          | 2.4       |
-------------------------

Now, I want to make a query in MySQL so that for user_id_fk 2 to get article_title,article_content from articles table with his respective categories, such as 2.1 , 3.1 and 4.1 .

I tried making some queries with inner joins but i wasn't successful to get the results i wanted.

Hope i was clear enough.

You can make this with subqueries. For example:

SELECT article_title, article_content 
FROM articles 
WHERE category_id IN (
  SELECT category_id_fk FROM user_categories WHERE user_id_fk = 1
)

Same example with join:

SELECT article_title, article_content 
FROM articles 
JOIN user_categories ON category_id = category_id_fk
WHERE user_id_fk = 1

Would this do it?

SELECT article_title,article_content 
FROM articles
WHERE category_id IN
(
  SELECT category_id
  FROM user_categories
  WHERE user_id_fk = 2
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM