Web Hosting Talk







View Full Version : MySQL Left Join


latheesan
10-05-2009, 02:02 PM
Hey,

I have two tables on my database:

product_list
- id
- product_name
- supplier_dropship_cost_price
- dropship_addon_percent
- supplier_bulkbuy_cost_price
- bulkbuy_addon_percent
- min_bulkbuy_quantity

my_cart
- id
- account_id
- product_id
- type
- pack_of
- amount

I want to show a list of items in the logged in user's cart (if any). I tried to retrieve the desired data by using the following query:

$query = "";
$query .= "SELECT ";
$query .= "`my_cart`.`id`, `my_cart`.`account_id`, `my_cart`.`product_id`, `my_cart`.`type`, `my_cart`.`pack_of`, `my_cart`.`amount` ";
$query .= "`product_list`.`supplier_dropship_cost_price`, `product_list`.`dropship_addon_percent`, `product_list`.`supplier_bulkbuy_cost_price`, `product_list`.`bulkbuy_addon_percent`, `product_list`.`min_bulkbuy_quantity`, `product_list`.`product_name` ";
$query .= "FROM `my_cart` ";
$query .= "LEFT JOIN `product_list` ON `product_list`.`id` = `my_cart`.`product_id` ";
$query .= "WHERE ( ";
$query .= "`my_cart`.`account_id` = %d";
$query .= ")";

When i ran the query in phpMyAdmin to test if it was correct and i got this error:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.`supplier_dropship_cost_price`, `product_list`.`dropship_addon_percent`,' at line 1

What im i doing wrong here? Thanks in advance for any help/tip.

bear
10-05-2009, 02:20 PM
`product_list`.`supplier_dropship_cost_price`

That looks like a field in a table? You're concatenating it so there's no space and no ".". It's being seen as "`product_list``supplier_dropship_cost_price`"

Or maybe not. Not my strong point, mySQL. ;)

aradapilot
10-05-2009, 02:33 PM
there is no comma after mycart.amount
you should not use appends to build this, it leaves room for error and makes the sql debugger see it all as one line, so it will always say line 1. in php, queries should look like:

$query="SELECT blah, blah,
more.blah,etc
FROM table
JOIN other_table ON blah
WHERE condition=blah
GROUP BY stuff, ORDER BY stuff
";

rather than using all of those .= statements.

latheesan
10-05-2009, 03:08 PM
thanks allot aradapilot, i forgot a comma lol.

tim2718281
10-06-2009, 02:56 AM
As you're coding PHP anyway, you might as well get the rows from the shopping cart, and then for each row get the relevant fields from the product table.

Using joins for this kind of thing seems horrendous.

Am I missing something?