MySQL Inner Join Query Multiple Tables(MySQL内连接查询多表)
问题描述
我正在尝试连接一些表格,布局示例如下:
I am trying to join up a few tables and examples of the layouts are below:
订单
user_id=7 pricing id=37
products_pricing
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 循环中列出每个产品名称.但是,当我为一个名为列表的表添加另一个 INNER JOIN 时,该表有一个 user_id 列,我需要为匹配的每一行获取一个 url,以便我可以将产品名称与 url 超链接,我也得到列表表中包含的所有内容作为上面的工作内容.我要么做错了,要么错过了一些东西.我花了几个小时试图弄清楚,但一直得到相同的结果.谁能帮帮我?
With this SQL i get an output giving me all the products from the user_id of 7 and it will list each products name in a while loop. However when I add another INNER JOIN for a table called listings, which has a user_id column and I need to grab a url for each row that matches so I can hyperlink the product names with the url I get everything contained in the listings table as well as the working stuff above. I'm either doing it very wrong or am missing something. I've spent a few hours trying to figure it out but keep getting the same result. Can anyone help me out?
推荐答案
试试这个:
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';
SQL Fiddle 演示
对于您在问题中发布的示例数据,这将为您提供:
SQL Fiddle Demo
For the sample data you posted in your question, this will give you:
| ID | NAME | URL | USER_ID | PRICING_ID |
------------------------------------------------------
| 33 | testproduct | test.com | 7 | 37 |
这篇关于MySQL内连接查询多表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:MySQL内连接查询多表
基础教程推荐
- SQL Server 2016更改对象所有者 2022-01-01
- Sql Server 字符串到日期的转换 2021-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01