MYSQL连接3个表,其中一个是链接表。

时间:2022-08-16 09:17:51

You would think this would be easy to find but after a lot of searching i cannot find an example that fits, probably because im using the wrong keywords to searching. I do realize this is pretty basic but i have tried so many variations and i just cant get it and a lot of the examples im seeing have a.tablename and b.tablename which just makes it confusing, while i do intent to read up on MYSQL further as i just about know the basics im just looking to get out of a hole so i can get my current code working for now.

您可能会认为这很容易找到,但是经过大量的搜索之后,我找不到一个适合的例子,可能是因为我使用了错误的关键词进行搜索。我意识到这是很基本的,但是我尝试了很多的变化,我无法得到它,我看到的很多例子都有。表名和b。tablename让我很困惑,我想进一步了解MYSQL,因为我知道一些基本的东西,我只是想从一个洞里出来,这样我就能得到我现在的代码。

Here is my SQL join which miserably fails:

下面是我的SQL join,它很糟糕地失败了:

SELECT faq.faq_title
FROM faq, category
INNER JOIN faq_link_category ON faq_link_category.category_id = category.category_id
WHERE faq_link_category.category_id =6

Basically i have 3 tables

基本上我有3张桌子。

faq table
---------
faq_id
faq_title

category table
---------
category_id
category_name

faq_link_category
---------
faq_id
category_id

Whats happening is that each FAQ can have more than 1 category associated so i set it up this way so i could basically do a search something on the lines of:

发生的是每个FAQ都有超过1个类别的关联所以我这样设置,所以我基本上可以在这些线上搜索一些东西

show me all faq titles where the category = 6

显示所有常见问题的标题,其中的类别= 6。

but im getting like 500 results instead of 4 or 5.

但是我得到了500个结果而不是4个或5个。

in short im arriving on a page with something like this index.php?=6

简单地说,我是用类似于这个index.php的东西到达一个页面的。

So i want to find all the faqs for that category where category_id = x which happens to be 6 in my example.

因此,我想找到这个类别的所有常见问题,在我的例子中,category_id = x恰好是6。

2 个解决方案

#1


2  

What you need is an outer join:

你需要的是一个外部连接:

SELECT faq_title
FROM faq f
JOIN faq_link_category flc
ON f.faq_id = flc.faq_id
JOIN category c
ON flc.category_id = c.category_id
WHERE flc.category_id = 6

#2


0  

Try this:

试试这个:

SELECT `faq`.`faq_title`
FROM `faq`
INNER JOIN `faq_link_category` ON `faq_link_category`.`category_id` = `faq`.`faq_id`
INNER JOIN `category` ON `faq_link_category`.`category_id` = `category`.`category_id`
WHERE `faq_link_category`.`category_id` = 6

#1


2  

What you need is an outer join:

你需要的是一个外部连接:

SELECT faq_title
FROM faq f
JOIN faq_link_category flc
ON f.faq_id = flc.faq_id
JOIN category c
ON flc.category_id = c.category_id
WHERE flc.category_id = 6

#2


0  

Try this:

试试这个:

SELECT `faq`.`faq_title`
FROM `faq`
INNER JOIN `faq_link_category` ON `faq_link_category`.`category_id` = `faq`.`faq_id`
INNER JOIN `category` ON `faq_link_category`.`category_id` = `category`.`category_id`
WHERE `faq_link_category`.`category_id` = 6