MySQL返回引用同一个表的行

时间:2012-11-15 11:53:30

标签: 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&的引用行值。行中未设置的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?

3 个答案:

答案 0 :(得分: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 link

答案 1 :(得分: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

答案 2 :(得分: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