Member Avatar for JayGeePee

I'm sure this is simple, but I'm having a time trying to figure out how to add two fields from two different tables together.

<?php 

        include_once('conn/db.php');

        $query = "SELECT SUM(`sold`) AS total FROM veggies";

        $stmt = $con->prepare( $query );
        $stmt->execute();

        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){

        extract($row);

        echo "<small><u>Plants Sold</u>: {$total}</small>";
        }

?>

The above code is just the total for one table field called sold.

I'm trying to add "sold" from the "veggie" table to another table with the same field name "sold", except it's from the "flower" table.

Essentially I'm shooting for sum(sold) from veggies + sum(sold) from flowers.

If you need a better explaination let me know.

Thanks.

You need to look at SQL joins.I'm in my mobile phone atm, or I would give an example.

Member Avatar for JayGeePee

I've looked into Join, but can't get a grasp on it. I get confused by the different types of Joins.

How about

SELECT (SELECT SUM(sold) FROM veggies) 
     + (SELECT SUM(sold) FROM flowers)
    AS total
Member Avatar for JayGeePee

Come on Reverend? It couldn't of been that simple. Haha! That actually worked, and I still can't believe it was that easy.

I actually had the below example at first, which didn't work of course.

SELECT (SUM(sold) FROM veggies),
       (SUM(sold) FROM flowers) 
        AS total

Why is the extra SELECT in the parentheses? If you don't mind me asking.

Thanks again, and I'm marking as solved

The only answer I can give is that if you don't use parentheses you get a syntax error ;-P

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.