我有3个表(up_1,up_2,up_3)。它们都具有相同的数据库结构(id,value,date,time)。我需要在特定日期列出它们。
例如,如果我选择2015年11月17日,它将在2015年11月17日列出所有数据。
以下是数据集的示例
ucp_1
----------------------------
id, value, date, time
----------------------------
1, 2, 17/11/2015, 09:00
2, 2, 17/11/2015, 10:00
ucp_2
----------------------------
id, value, date, time
----------------------------
1, 2, 17/11/2015, 11:00
2, 2, 17/11/2015, 12:00
ucp_3
----------------------------
id, value, date, time
----------------------------
1, 2, 17/11/2015, 13:00
2, 2, 17/11/2015, 14:00
我想要显示的结果
结果
-------------------------------------------------
value_ucp1, value_ucp2, value_ucp3, date, time
-------------------------------------------------
2, NULL, NULL, 17/11/2015, 09:00
2, NULL, NULL, 17/11/2015, 10:00
NULL, 2, NULL, 17/11/2015, 11:00
NULL, 2, NULL, 17/11/2015, 12:00
NULL, NULL, 2, 17/11/2015, 13:00
NULL, NULL, 2, 17/11/2015, 14:00
是否可以通过SQL Query实现这些结果?
答案 0 :(得分:1)
您可以使用UNION ALL
all来组合不同的表格。
SELECT value AS ucp_1_Value,
NULL AS ucp_2_Value,
NULL AS ucp_3_Value,
`date`,
`time`
FROM ucp_1
WHERE `date` = '17-11-2015'
UNION ALL
SELECT NULL AS ucp_1_Value,
value AS ucp_2_Value,
NULL AS ucp_3_Value,
`date`,
`time`
FROM ucp_2
WHERE `date` = '17-11-2015'
UNION ALL
SELECT NULL AS ucp_1_Value ,
NULL AS ucp_2_Value,
value AS ucp_3_Value,
`date`,
`time`
FROM ucp_3 WHERE `date` = '17-11-2015'
希望这有帮助。
答案 1 :(得分:1)
尝试将结果与UNION ALL合并为子查询,如此
SELECT
merged.*
FROM (
SELECT
value AS value_ucp_1,
NULL AS value_ucp_2,
NULL AS value_ucp_3,
date,
time
FROM up_1
UNION ALL SELECT
NULL,
value,
NULL,
date,
time
FROM up_2
UNION ALL SELECT
NULL,
NULL,
value,
date,
time
FROM up_3) AS merged
WHERE merged.date = '17-11-2015'
答案 2 :(得分:0)
只是另一种观点。
<强>查询强>
select case when t.ucp_id = 'ucp_1' then t.value_ucp end as value_ucp1,
case when t.ucp_id = 'ucp_2' then t.value_ucp end as value_ucp2,
case when t.ucp_id = 'ucp_3' then t.value_ucp end as value_ucp3,
t.`date`,t.`time`
from
(
select 'ucp_1' as ucp_id,value as value_ucp,`date`,`time` from ucp_1
union all
select 'ucp_2' as ucp_id,value as value_ucp,`date`,`time` from ucp_2
union all
select 'ucp_3' as ucp_id,value as value_ucp,`date`,`time` from ucp_3
)t;
答案 3 :(得分:0)
重新组织数据库结构。使用您提到的结构创建一个表:
Table VDT
id_VDT, value, date, time
与其他字段链接到第一个字段的树表:
Table_A
id_VDT, {first table fields}
Table_B
id_VDT, {second table fields}
Table_C
id_VDT, {third table fields}
然后运行查询:
SELECT * FROM VDT, Table_A A, Table_B B, Table_C C
WHERE VDT.Date = {your date} AND
VDT.id_VDT=A.id_VDT AND VDT.id_VDT=B.id_VDT AND VDT.id_VDT=C.id_VDT
ORDER BY {your need}