Member Avatar

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.

Recommended Answers

How about

SELECT (SELECT SUM(sold) FROM veggies) 
     + (SELECT SUM(sold) FROM flowers)
    AS total
Jump to Post

All 5 Replies

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

Member Avatar

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

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 1.18 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.