[英]Mysql - Join 2 tables if records in third table
I have 3 tables我有 3 张桌子
Table 1 = Customers表 1 = 客户
CREATE TABLE `Customers` (
`customer_id` int NOT NULL,
`name` varchar(5) NOT NULL
)
Table 2 = Wallposts表 2 = 墙贴
CREATE TABLE `wallposts` (
`customer_id` int NOT NULL,
`post` varchar(255) NOT NULL
)
Table 3 = Friend_list表 3 = Friend_list
CREATE TABLE `friends` (
`customer_id` int NOT NULL,
`friend_id` int NOT NULL
)
I need to get a list of all wallposts by friends of a specific customer_id.我需要获取特定 customer_id 的朋友的所有墙贴列表。 The friend_id is taken from the customer_id in the customers table
friend_id 取自 customers 表中的 customer_id
Example output示例 output
customer_id 2, name John, message hello world
customer_id 4, name Susan, message Customer service sucks
customer_id 7, name Philip, message Customer service is great
All those posts belong to friends of customer with customer_id 1.所有这些帖子都属于 customer_id 为 1 的客户的朋友。
A series of joins should do the trick一系列连接应该可以解决问题
SELECT c.customer_id, c.name, w.post
FROM friends f
JOIN customer c ON f.friend_id = c.customer_id
JOIN wallposts w ON c.customer_id = w.customer_id
WHERE f.customer_id = 1
Another way to do it can be as below另一种方法可以如下
SELECT
customers.customer_id, customers.name, wallposts.posts
FROM
wallposts
INNER JOIN customers ON wallposts.customer_id = customers.customer_id
WHERE wallposts.customer_id IN(SELECT friend_id FROM friends WHERE customer_id = 1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.