I have two examples of tables I am using
I am using the output to build arrays so my output needs to be a single column
First table is a list of products
PRODUCT ID PRODUCT_NAME
01 product1
02 product2
03 product3
04 product4
05 product5
06 product6
07 product7
08 product8
09 product9
10 product10
11 product11
12 product12
Table two is a list of purchases
SALESID PRODUCT_NAME USERID DATE
01 product1 001ABC 11-10-2012
02 product5 001ABC 11-11-2012
03 product1 002XYZ 11-11-2012
04 product12 001ABC 11-13-2012
05 product7 001ABC 11-13-2012
06 product3 002XYZ 11-14-2012
07 product11 002XYZ 11-14-2012
Now what I need is if I supply a USERID like 001ABC
I need the output to be a 1 if the USERID matches the one I supply and(which it should automatically)it appears in the product table and I need it to show a 0 if it just appears in the products table
So two examples of the above two tables and these two USERIDs would look like this
USERID 001ABC supplied
yields
OUTPUT
1
0
0
0
1
0
1
0
0
0
0
1
USERID 002XYZ supplied
yields
OUTPUT
1
0
1
0
0
0
0
0
0
0
1
0
Using CASE statements has failed or I was not getting the syntax correct
I am using PHP and MYSQL
My current query worked good as long as I had a single USERID but failed when I tried filtering by the userID as well
PHP/MYSQL query:
SELECT (PURCHASES.PRODUCT_NAME IS NOT NULL) AS purchased
FROM PRODUCTS
LEFT JOIN PURCHASES
ON PRODUCT_NAME = PRODUCT_NAME ORDER BY 1
I am not sure what I am doing wrong.
When I added another user with two purchases the results seemed to simply add two more rows to the output so the output would have had 14 rows instead of the original 12 as in the examples I show.
How can I can get a single column output with a total amount of records that equals the total amount of products each row set to zero except when a match is found in the purchases table identified by the product name then instead of zero a 1 is in the output.
Here’s the query you want. You need to order the results by the product ID; you’re ordering them by the 0/1 value in the output column, which of course destroys the usefulness of that column.
You also need to do a summary on the filtered purchases table to figure out whether there have been any purchases of the specific product. That’s the subquery “b”.
Finally, you left join from products to purchases, because you want exactly one row in your output resultset for each product.
See this SQL Fiddle for example. http://sqlfiddle.com/#!2/6e985/12/0