简体   繁体   中英

Using two inner join tables

I have come up with two queries, both use an inner join on two different tables.

Query 1

SELECT PRODUCTS.CODE, PRODUCTS.REFERENCE, PRODUCTS.TAXCAT, PRODUCTS.DISPLAY,PRODUCTS.NAME, PRODUCTS.PRICEBUY, PRODUCTS.PRICESELL, CATEGORIES.NAME AS CATEGORY
FROM PRODUCTS INNER JOIN CATEGORIES ON PRODUCTS.CATEGORY = CATEGORIES.ID;

Query 2

SELECT PRODUCTS.CODE, PRODUCTS.REFERENCE, PRODUCTS.TAXCAT, PRODUCTS.DISPLAY,PRODUCTS.NAME, PRODUCTS.PRICEBUY, PRODUCTS.PRICESELL,STOCKCURRENT.UNITS AS UNIT FROM PRODUCTS INNER JOIN STOCKCURRENT ON STOCKCURRENT.PRODUCT = PRODUCTS.ID;

Both queries run fine on their own, when I try to use both inner joins together I get errors. This is what I came up with on my own. I'm having trouble understanding the syntax to achieve this.

SELECT PRODUCTS.CODE, PRODUCTS.REFERENCE, PRODUCTS.TAXCAT,
PRODUCTS.DISPLAY,PRODUCTS.NAME, PRODUCTS.PRICEBUY,
PRODUCTS.PRICESELL,STOCKCURRENT.UNITS AS UNIT FROM PRODUCTS INNER JOIN
STOCKCURRENT ON STOCKCURRENT.PRODUCT = PRODUCTS.ID, CATEGORIES.NAME AS
CATEGORY FROM PRODUCTS INNER JOIN CATEGORIES ON PRODUCTS.CATEGORY =
CATEGORIES.ID;

Thank you.

Your attempted query has several syntax problems. Assuming you just want to join together the three tables, you may try the following query:

SELECT
    p.CODE,
    p.REFERENCE,
    p.TAXCAT,
    p.DISPLAY,
    p.NAME,
    p.PRICEBUY,
    p.PRICESELL,
    s.UNITS AS UNIT,
    c.NAME AS CATEGORY
FROM PRODUCTS p
INNER JOIN STOCKCURRENT s
    ON s.PRODUCT = p.ID
INNER JOIN CATEGORIES c
    ON p.CATEGORY = c.ID;

Note that I introduced table aliases here. These aliases can be used elsewhere in the query to avoid having to repeat the entire table name.

By the way, I can also see taking a union of your two original queries. But without expected output, it was not entirely clear what you want.

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