[英]Joining 3 tables Many to many relationship single query
How can I write one MYSQL query for the following 如何为以下内容编写一个MYSQL查询
I have 3 tables 我有3张桌子
I know the logged in user_id
is 25 我知道登录的user_id
是25
Users(id,first_name,last_name)
, Users(id,first_name,last_name)
,
userproduducts(user_id,product_id)
, userproduducts(user_id,product_id)
,
Product(id,title,description,price)
userproducts
is a many to many resolved table userproducts
是一个多对多的解析表
how can I write a query that will get me the first_name
, last_name
of the user with id=25
and get everything in the product table of products where user_id = 25
in userproducts table?? 如何编写一个查询,它将获取id=25
的用户的first_name
, last_name
,并获取userproducts表中user_id = 25
的产品的product表中的所有内容?
thank you 谢谢
A simple straightforward JOIN
will give you what you want: 一个简单直接的JOIN
将为您提供您想要的:
SELECT
u.first_name,
u.last_name,
p.*
FROM users As u
INNER JOIN userproducts AS up ON up.user_id = u.id
INNER JOIN product AS p ON up.product_id = p.id
WHERE u.id = 25;
This is done with two joins. 这是通过两个连接完成的。 They should be LEFT JOINS if you want to get the users who do not have products. 如果您想要获得没有产品的用户,他们应该是LEFT JOINS。
SELECT u.first_name, u.last_name, p.*
FROM users u
LEFT JOIN userproducts up ON u.id = up.user_id
LEFT JOIN product on up.product_id = p.id
WHERE p.id = 25
The product information will be null in the case where there are no products. 在没有产品的情况下,产品信息将为空。 If you don't want the null products, use the INNER JOIN, also just written as JOIN that is found in the previous answers. 如果您不想要null产品,请使用INNER JOIN,也可以写为在前面的答案中找到的JOIN。
SELECT u.first_name, u.last_name, p.*
FROM users u
JOIN userproducts up ON u.id = up.user_id
JOIN product on up.product_id = p.id
WHERE p.id = 25
try this 尝试这个
SELECT
ut.first_name,
ut.last_name,
pt.*
FROM users As ut
INNER JOIN userproducts AS upro ON upro.user_id = ut.id
INNER JOIN product AS pt ON upro.product_id = pt.id
WHERE ut.id = 25;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.