MySQL Query:如何做到这一点?

时间:2013-05-27 07:43:20

标签: sql

我知道这张桌子不是应该的,但它只是,它不能改变。

我的表:

|carID  | car1      | car2      | car3      |
-------------------------------------------------
|   1   | someCar 1 | someCar 2 | someCar 3 |
-------------------------------------------------

我想要以下结果,就像它应该在关系表中一样:

|carID  |car        |
---------------------
|1      | someCar 1 |
|1      | someCar 2 |
|1      | someCar 3 |

有人知道怎么做吗?

我试过这样的事情:

SELECT carId, car1, car2, car3 FROM cars WHERE carId = '1' GROUP BY car1, car2, car3

3 个答案:

答案 0 :(得分:2)

UNION

SELECT   CarID, car1 car FROM MyTable
UNION ALL
SELECT   CarID, car2 car FROM MyTable
UNION ALL
SELECT   CarID, car3 car FROM MyTable

答案 1 :(得分:0)

尝试UNION ALL

SELECT CarID, Car1 FROM myTable WHERE carID='1'
UNION ALL
SELECT CarID, Car2 FROM myTable WHERE carID='1'
UNION ALL
SELECT CarID, Car3 FROM myTable WHERE carID='1'

答案 2 :(得分:0)

创建三个选择的联合:

SELECT carID, car1 FROM cars WHERE carID = '1'
UNION ALL
SELECT carID, car2 FROM cars WHERE carID = '1'
UNION ALL
SELECT carID, car3 FROM cars WHERE carID = '1'

请注意您需要使用UNION ALL,而不仅仅是UNION,因为仅UNION会遗漏重复内容。例如,如果car2car3相同,则结果只包含两条​​记录。