我有两个表,名为t_header和t_detail。
此数据标题
ID | doc_num | promotion
1 0001 0
2 0002 1
此数据详情
ID | doc_num | item | price
1 0001 2 100
2 0001 3 170
3 0001 4 102
4 0001 5 105
5 0002 3 120
6 0002 4 99
7 0002 7 165
如果促销= 1,那么价格详细将采取详细的数据促销价格,对于上表,如果item = 3然后将价格= 120,因为具有doc_num 002 promo = 1的项目,如果没有促销它将采用价格docnum 001,001 num doc标准价格和逐项
输出
ID | doc_num | item | price | promotion
1 0001 2 100 0
5 0002 3 120 1
6 0002 4 99 1
4 0001 5 105 0
7 0002 7 165 0
答案 0 :(得分:0)
我猜您需要选择促销价格,否则您需要正常价格。因此,您应该在LEFT JOIN之后使用IF语句选择列。 此查询可能有所帮助:
SELECT
if(td_prom.ID, td_prom.ID, td_norm.ID) as ID,
th.doc_num,
if(td_prom.price, td_prom.price, td_norm.price) as price,
if(td_prom.item, td_prom.item, td_norm.item) as item,
th.promo
FROM
t_header th
LEFT JOIN t_detail as td_norm ON th.doc_num = td_norm.doc_num AND th.promo = 0
LEFT JOIN t_detail as td_prom ON th.doc_num = td_prom.doc_num AND th.promo = 1
GROUP BY item
答案 1 :(得分:0)
正如我在您想要的结果中看到的那样,您不希望项目显示两次。在此旁边,我假设您的数据库中有一个项目表。然后我提出了这个问题。 第一部分是提取促销中的项目。 第二部分仅添加不在促销中的项目,但不包括在其上有促销的项目。
SELECT d.id, d.doc_num, d.item, d.price, h.promo
FROM items AS i
INNER JOIN detail AS d ON i.id = d.id
INNER JOIN header AS h ON h.doc_num = d.doc_num AND h.promo = 1
UNION ALL
SELECT nopromo.*
FROM (SELECT d.id, d.doc_num, d.item, d.price, h.promo
FROM items AS i
INNER JOIN detail AS d ON i.id = d.id
INNER JOIN header AS h ON h.doc_num = d.doc_num AND h.promo = 0) AS nopromo
LEFT OUTER JOIN
(SELECT d.id, d.doc_num, d.item, d.price, h.promo
FROM item AS i
INNER JOIN detail AS d ON i.id = d.id
INNER JOIN header AS h ON h.doc_num = d.doc_num AND h.promo = 1) AS ipromo
ON nopromo.item = ipromo.item
WHERE ipromo.id IS NULL
ORDER BY item
结果
+---+--------+-----+------+------+
|id |doc_num |item |price |promo |
+---+--------+-----+------+------+
|1 |0001 |2 |100 |0 |
|5 |0002 |3 |120 |1 |
|6 |0002 |4 |99 |1 |
|4 |0001 |5 |105 |0 |
|7 |0002 |7 |165 |1 |
+---+--------+-----+------+------+