4

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

+----+--------------+-------+----------------+------------+
| 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&的引用行值price......在同一个结果集中。

因此,例如,我的结果集应如下所示:

[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 做到这一点?

4

3 回答 3

2

我认为在你的情况下这会很好:

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链接

于 2012-11-15T12:48:58.603 回答
0

这应该这样做。我现在没有可能检查语法,但如果你在运行它时遇到问题,我会在稍后查看。

select id , 
      (if bulk_reference > 0 then (select p1.product_name from product p1 where p1.id = p3.bulk_reference)  else product_name end if) ,
      (if bulk_reference > 0 then (select p2.price from product p2 where p2.id = p3.bulk_reference) else price end if) , 
       bulk_reference, 
       bulk_count 
from products p3
于 2012-11-15T12:03:11.433 回答
0

你可以试试这个查询:

SELECT * 
FROM table 
WHERE bulk_reference = 0

UNION

SELECT t1.id, t2.product_name, t2.price, t1.bulk_reference, t1.bulk_count 
FROM table t1
JOIN table t2 ON t2.id = t1.bulk_reference
于 2012-11-15T12:05:31.763 回答