简体   繁体   中英

Query from two tables

I have to combine datas from two tables i have created in mySQL.

im supposed to figure out how many of each product that has arrived on any given day.

I have created the following query:

SELECT SUM(Amount) Shipment.Arrival_date, 
       Shipment.Shipment_ID, 
       `Product shipment`.Product_Code, 
       `product shipment`.Shipment_ID, 
       `product Shipment`.Amount 
FROM `Product shipment`, `shipment` 
WHERE `product Shipment`.Shipment_ID=`Product Shipment`.Product_code 
    AND Arrival_date = '2014-01-01

My two respective tables are called Shipment and Product Shipment.

Furthermore i have in my shipment table a collumn that describes the day of arrival, and the shipment_ID which is a primary key to a shipment_ID in my product shipment table.

In my product shipment table, the shipment_ID is described by a product_code and the Amount of the product.

My query returns with an #1064 error. Any suggestions on how to solve?

try this :

SELECT SUM(ps.Amount),
    s.Arrival_date, 
    s.Shipment_ID, 
    ps.Product_Code, 
    ps.Shipment_ID, 
    ps.Amount 
FROM 
    `Product shipment` AS ps,
    `shipment` AS s
WHERE 
    ps.Shipment_ID=ps.Product_code 
    AND 
        s.Arrival_date = '2014-01-01'

Notice that your join link ps table to ps table, it may be a wanted behavior but you never join ps to s

At least you are missing either a comma between SUM(Amount) and Shipment.Arrival_date or missing an 'as' from the same spot. In addtition, Arrival_date in WHERE clause is missing an ' - is it in code or did you just forget to paste it here?

Also, depending on your MySQL settings and OS where MySQL is running on, differencies in table.column name capitalization could cause problems. You have 'Product Shipment

You have missed a comma after the aggregate function in your query. Additionally you had the column you were trying to sum in the select field, which (almost always) is wrong.

This should work:

select
    sum(ps.Amount),
    // You forgot the comma after this aggregate function
    sh.Arrival_date, 
    sh.Shipment_ID, 
    ps.Product_Code, 
    ps.Shipment_ID
from 
    `Product shipment` ps
        join `shipment` sh
            on ps.Shipment_ID=.Product_code 
where
    Arrival_date = '2014-01-01'
group by
    sh.Arrival_date, 
    sh.Shipment_ID, 
    ps.Product_Code, 
    ps.Shipment_ID

Also, you really should read this lengthy Q&A that I put together to help in cases exactly like this, where you have an issue with your query you don't understand, some folks come to help - and while the answers here might solve the issue (we hope) you still don't really get what you did wrong.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM