我有一个如下所示的mysql表:
+------+-------+-------+----------+------------+
| id | name | RowSZ | TimeSZ | DateSZ |
+------+-------+-------+----------+------------+
| 1 | namex | 2 | 12:00:00 | 2018-06-29 |
+------+-------+-------+----------+------------+
| 2 | namey | 1 | 10:00:00 | 2018-06-30 |
现在,我想填充一个如下所示的html表:
+-------+----------+----------+------------+
| name | Timerow1 | Timerow2 | DateSZ |
+-------+----------+----------+------------+
| namex | | 12:00:00 | 2018-06-29 |
+-------+----------+----------+------------+
| namey | 10:00:00 | | 2018-06-30 |
Timerow1和Timerow2取决于值“ RowSZ”。
我现在的SQL查询:
$sql = "SELECT *, DATE_FORMAT(DateSZ, '%d-%m-%y') AS DateSZ FROM table1 ORDER BY DateSZ ASC";
如何正确填充Timerow1和Timerow2两行?
答案 0 :(得分:1)
使用UNION
处理这两种情况。
SELECT name, NULL AS TimeRow1, TimeSZ AS TimeRow2, DateSZ
FROM yourTable
WHERE RowSZ = 2
UNION
SELECT name, TimeSZ AS TimeRow1, NULL AS TimeRow2, DateSZ
FROM yourTable
WHERE RowSZ = 1
ORDER BY DateSZ