【问题标题】:SQL how to tie tables togetherSQL如何将表绑定在一起
【发布时间】:2026-02-11 11:45:02
【问题描述】:

我的教授说我没有在表之间绑定,现在我想问如何绑定表,这是我做错的两个例子。

Query2 - 表之间没有联系

SELECT CustomerID, CompanyName, [Order Details].UnitPrice
FROM Customers, [Order Details]
WHERE ((([Order Details].UnitPrice)>=50));

Query3 - 表之间没有联系

SELECT ProductID, ProductName, ShippedDate
FROM Products, Orders
where Orders.ShippedDate between ('1996-07-01') and ('1996-07-31')
ORDER BY Orders.ShippedDate;

【问题讨论】:

    标签: sql join select


    【解决方案1】:

    基本上,您的查询缺少两个表之间的连接条件。没有它,您将获得两个表中行的笛卡尔积。

    这就是join 语法发挥作用的地方。例如对于第二个查询,假设productsorders 通过列product_id 关联:

    select p.productid, p.productname, o.shippeddate
    from products p
    inner join orders o on o.product_id = p.product_id
    where o.shippeddate >= '1996-07-01' and o.shippeddate < '1996-08-01'
    order by o.shippeddate;
    

    查询的其他改进:

    • 表别名使查询更易于编写和阅读
    • 日期比较的半开间隔很方便:它们可以正确处理日期的时间部分(如果有)

    【讨论】: