[英]How to compare value between two column in one row, if different then create another row?
I have the following table in MySQL: 我在MySQL中有下表:
id | item_id | uom | uom1
1 1 kg box
When i select all from the table, it will display one row. 当我从表中选择全部时,它将显示一行。
I want to make it to display two row if the uom and uom1 is different. 如果uom和uom1不同,我想使其显示两行。
For example, uom = kg and uom1 = box then result will show 例如,uom = kg和uom1 = box,则结果将显示
id | item_id | uom
1 1 kg
2 1 box
if both uom and uom1 is same(kg) then only one row will show 如果uom和uom1相同(kg),则仅显示一行
id | item_id | uom
1 1 kg
Is it possible to do it using sql? 是否可以使用sql做到这一点? Then i will just loop it at my view. 然后我将其循环显示。
select
@rownum := @rownum + 1 AS id,
T.*
from (
select `item_id`, `uom`
from Table1
union
select `item_id`, `uom1` as `uom`
from Table1
) T , (SELECT @rownum := 0) r
| id | item_id | uom |
|----|---------|-----|
| 1 | 1 | kg |
| 2 | 1 | box |
One simple way of doing it would be 一种简单的方法是
select id, item_id, uom from tbl union
select id, item_id, uom1 from tbl
UNION
will by default filter out duplicate lines. 默认情况下, UNION
会过滤掉重复的行。 There is no need for further "tricks" ... 不需要其他“技巧” ...
@Neeraj Wadhwa suggested the second line to be changed to: @Neeraj Wadhwa建议将第二行更改为:
select id, item_id, uom1 as uom from tbl
This is possible and will produce the same result, but it is not really necessary. 这是可能的,并且将产生相同的结果,但并不是必须的。 The column names in a UNION
construct will be determined by the first select statement anyway. 无论如何, UNION
构造中的列名称将由第一条select语句确定。
I think the simple union should help here: 我认为简单的工会应该在这里有所帮助:
select distinct * from (
select id, item, uom1 as uom from stuff
union
select id, item, uom2 as uom from stuff
) as unionised
order by unionised.id
Hre's the fiddle: http://sqlfiddle.com/#!9/ece687/1 赫尔的小提琴: http ://sqlfiddle.com/#!9/ece687/1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.