views:

73

answers:

1

EDIT: Changed the question to be more clear.

EDIT 2: The intention here to create an "add to list" and "remove from list" when outputting a catalog (I don't want a user to be able to add an item more than once)

First of all, I'm not sure if this should be done in Coldfusion or MySQL.

I have a query of items that retrieves items in a catalog. I have a second query that retrieves items from a user's list. My objective is to find out if an item is already present in a user's list when outputting the first query (the items catalog).

items(itemId, itemName)

users_items(itemId,memberId)
+4  A: 

Can an item belong to more than one catalog? If so, you can't tell which catalog based on the USERS_ITEMS table to render the list properly.

Otherwise, I think you could do with using a LEFT JOIN:

   SELECT i.itemid,
          i.itemname,
          ui.memberid
     FROM ITEMS i
LEFT JOIN USERS_ITEMS ui ON ui.itemid = i.itemid
                        AND ui.memberid = ?

...which'll return a result like (I omitted itemname):

itemid   memberid
--------------------
1        1234
2        NULL
3        1234

Where you see NULL, tells you that the member hasn't ordered the item.

In Coldfusion, you just have to setup the page to handle the add or remove option appropriately based on the presence of a value or NULL.

  • only allow someone to "add to list" when the memberid is null (IE: item 2)
  • if memberid is not null (IE items 1 & 3) --provide the "remove from list" option.
OMG Ponies
Sorry, I'm finding this a bit difficult to follow... an item can belong to more than one user, and a user can have many items... my tables are users(userid), items(itemid), users_items(userid,itemid)... I'm going to try and disect what you gave me, but I must say I'm struggling a bit...
Mel
@Mel: I updated to provide a resultset, and freshed out the algorithm a little more. I don't know Coldfusion, or I'd provide a snippet.
OMG Ponies
awesome! I just tested this and it works!
Mel
Additional question... the problem with that query is that it loads all the rows in the items table... the catalog page only displays 8 items at a time... it would be much quicker to run this against 8 items than all the items in the items table... is this possible?
Mel
@Mel: What you're asking about is called "pagination". In MySQL, it means using a query as is, but limiting the number of rows by using the [LIMIT syntax](http://php.about.com/od/mysqlcommands/g/Limit_sql.htm)
OMG Ponies