0

I was wondering if somebody could help.

I have a products table and in the table a column called master_colours.

I have 3 columns in the table called stock_id, master and colour, the master column tells it which stock_id to link to like so...

stock_id, master, colour
12345, '', ''
aaa, '12345', 'red'
bbb, '12345', 'blue'
ccc, '12345', 'green'

In the master_colours column I want it to be updated to the value of how many colours the master product will have so in the example above it will be 3.

I have so far the following code which returns the error #1242 - Subquery returns more than 1 row.

UPDATE products AS main
SET main.master_colours = (SELECT master.stock_id FROM (
SELECT p.stock_id, COUNT(DISTINCT(m.colour))
FROM products AS p, products AS m
WHERE m.master = p.stock_id AND m.colour != ''
GROUP BY p.stock_id) AS master)

I understand why it is doing it because I have grouped by the stock_id but if I dont do this then it counts all colours in the table rather than the colours linked to that stock id.

The logical thing to me would be to do this...

UPDATE products AS main
SET main.master_colours = (SELECT master.stock_id FROM (
SELECT p.stock_id, COUNT(DISTINCT(m.colour))
FROM products AS p, products AS m
WHERE m.master = p.stock_id AND m.colour != '' AND p.stock_id = main.stock_id
GROUP BY p.stock_id) AS master)

but obviously this doesnt work because main.stock_id is outside the sub query.

Can anyone please point me in the right direction?

Thanks

1
  • Please provide correct schema of products table. Commented Oct 13, 2014 at 16:56

1 Answer 1

1

Are you looking for something like this?

UPDATE products p JOIN
(
  SELECT master, COUNT(*) total
    FROM products
   GROUP BY master
) q ON p.stock_id = q.master
   SET p.master_colours = total;

That is assuming that you only have 1 level deep hierarchy

Outcome:

| STOCK_ID | MASTER | COLOUR | MASTER_COLOURS |
|----------|--------|--------|----------------|
|    12345 |        |        |              3 |
|      aaa |  12345 |    red |         (null) |
|      bbb |  12345 |   blue |         (null) |
|      ccc |  12345 |  green |         (null) |

Here is SQLFiddle demo

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.