MySQL返回引用同一个表的行

假设我有一张表格看起来像这样:

+----+--------------+-------+----------------+------------+
| id | product_name | price | bulk_reference | bulk_count |
+----+--------------+-------+----------------+------------+
| 1  | xxxx         | 11.99 | 0              | 0          |
+----+--------------+-------+----------------+------------+
| 2  | zzzz         | 22.99 | 0              | 0          |
+----+--------------+-------+----------------+------------+
| 3  |              |       | 2              | 10         |
+----+--------------+-------+----------------+------------+

我可以选择所有产品等,没问题.但是 – 我需要做的是返回所有产品,但行WHERE bulk_reference> 0需要返回product_name&的引用行值.行中未设置的价格…在同一结果集中.

例如,我的结果集看起来应该是这样的:

[0] => [id] = 1
       [product_name] = xxxx
       [price] = 11.99
       [bulk_reference] = 0
       [bulk_count] = 0

[1] => [id] = 2
       [product_name] = zzzz
       [price] = 22.99
       [bulk_reference] = 0
       [bulk_count] = 0

[2] => [id] = 3
       [product_name] = zzzz
       [price] = 22.99
       [bulk_reference] = 2
       [bulk_count] = 10

我怎么能只用MySQL做这个?

最佳答案 我认为这样你的情况会很好:

select
    P1.id,
    IF(bulk_reference>0,(select product_name from Products P2 where P2.id=P1.bulk_reference),P1.product_name) as product_name,
    IF(bulk_reference>0,(select price from Products P2 where P2.id=P1.bulk_reference), P1.price) as price,
    P1.bulk_reference,
    P1.bulk_count
from Products P1;

这是sqlfiddle link

点赞