简体   繁体   中英

Subquery driving NULL values into outer query

I keep getting NULL rows in a nested query

Provided we have the following tables:

  1. 'article' containing article information

  2. 'bom' containing an mn relation between article IDs, forming a bill of materials

Not every article is appearing in the 'bom' table - some will neither appear as parent nodes, nor as child nodes in any bill of materials.

I'm trying to get a list of articles and include a concatenated string containing the bill of materials, in case my article is a parent node.

Hence I'm trying this query structure in MySQL:

SELECT
a.id,
a.name,
(SELECT group_concat(
   bom.quantity, ' times ',
   a_child.partnumber, ' ',
   a_child.name)
   FROM
      bom
      left outer join article a_child on a_child.id = bom.child_article
   WHERE
      bom.parent_article = a.id
) myBOM
from article a

The query should also return plain articles which are not a parent of any bom or a part of any bom.

In case a parent article does have an associated bom, it should be outlined on the myBOM column. Otherwise the column should just be empty.

I am now getting some lines returning NULL in the outer query, while others work just fine - and I can't figure out what is driving some to work, others to fail.

How do I go about this?

Update : some sample data:

Table article :

id   | name    | partnumber
-----+---------+------------
1    | desk    | P001
2    | leg     | P002
3    | board   | P003

Table bom :

id   | parent_article | child_article | quantity
-----+----------------+---------------+---------
1    | 1              | 2             | 4
2    | 1              | 3             | 1

Expected output:

id   | name       | myBOM
-----+------------+-------------------------------------
1    | table      | 4 times P002 leg, 1 times P003 board
2    | leg        |
3    | board      |

I guess tables should be swaped and group_concut wrap with IFNULL instruction... The following query returns required result

SELECT
a.id,
a.name,
(SELECT IFNULL(group_concat(
   bom.quantity, ' times ',
   a_child.partnumber, ' ',
   a_child.name), '')
   FROM
      article a_child
      left outer join bom on a_child.id = bom.child_article
   WHERE
      bom.parent_article = a.id
) myBOM
from article a

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM