我正在尝试连接几个表格,下面是布局示例:
订单
user_id=7 pricing id=37
products_pricing
id=37 product_id=33
产品
id=33 name=test product
SQL
SELECT *
FROM orders
INNER JOIN products_pricing
ON orders.pricing_id = products_pricing.id
INNER JOIN products
ON products_pricing.product_id = products.id
WHERE orders.user_id = '7' ");
选
id=233 user_id=7 url=test.com
使用这个SQL我得到一个输出,给我user_id为7的所有产品,它将在while循环中列出每个产品名称。然而,当我为一个名为listing的表添加另一个INNER JOIN时,它有一个user_id列,我需要为匹配的每一行抓取一个url,所以我可以用url超链接产品名称,我也可以获得列表中包含的所有内容作为上面的工作内容。我要么做得非常错,要么错过了什么。我花了几个小时试图找出它,但一直得到相同的结果。任何人都可以帮助我吗?
答案 0 :(得分:23)
试试这个:
SELECT
p.id,
p.name,
l.url,
o.user_id,
o.pricing_id
FROM orders AS o
INNER JOIN products_pricing AS pp ON o.pricing_id = pp.id
INNER JOIN products AS p ON pp.product_id = p.id
INNER JOIN listings AS l ON l.user_id = o.user_id
WHERE o.user_id ='7'
AND l.id = 233
AND l.url = 'test.com';
对于您在问题中发布的样本数据,这将为您提供:
| ID | NAME | URL | USER_ID | PRICING_ID |
------------------------------------------------------
| 33 | testproduct | test.com | 7 | 37 |
答案 1 :(得分:0)
是的,这可以使用INNER join本身完成。并在select语句中获取select列。
SELECT
p.id,
p.name,
l.url,
o.user_id,
o.pricing_id
FROM orders AS o
INNER JOIN products_pricing AS pp ON o.pricing_id = pp.id
INNER JOIN products AS p ON pp.product_id = p.id
INNER JOIN listings AS l ON l.user_id = o.user_id
WHERE o.user_id ='7'
AND l.id = 233
AND l.url = 'test.com';