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_nameprice

たとえば、結果セットは次のようになります。

[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 に答える