views:

65

answers:

2

I want to be able to use multiple keys to join two tables. Is the following possible?

SELECT * FROM items LEFT JOIN issues USING (item_id OR order_id)

This is a simplified version of what i am doing. using MySQL 5.1.36 in case that matters.

UPDATE: I want all the issues joined, using item_id or order_id. So there could be multiple issues per item. i vaguely remember something about group by but i never could figure out how to join multiple records to one.

would be nice to get something that looks like this:

array {
  item_id => 1,
  item_name => 'test item',
  issues => array {
    [0] => array { issue_id => 1, issue_type => 'test issue'},
    [1] => array { issue_id => 2, issue_type => 'test issue'}
  }
}

Hopefully that makes sense. basically, an array of the issues as part of the mysql result

+1  A: 

I would use a union:

select * from items left join issues using (item_id)
union all
select * from items left join issues using (order_id)
Pablo Santa Cruz
+2  A: 

The list of columns used with the USING clause should be comma separated:

SELECT * 
FROM items 
LEFT JOIN issues 
USING (item_id, order_id)

which is same as:

SELECT * 
FROM items 
LEFT JOIN issues 
ON tab1.item_id = tab2.item_id AND tab1.order_id = tab2.order_id

If you want to match on either of the two column equalities you can use an OR instead of AND

SELECT * 
FROM items 
LEFT JOIN issues 
ON tab1.item_id = tab2.item_id OR tab1.order_id = tab2.order_id
codaddict