如何连接多个SQL查询的结果

时间:2016-11-21 15:02:05

标签: mysql sql

我想显示SELECT中定义的必需列,一旦执行了一个条件并打印条件的结果,我希望SELECT中的新指定列从另一个where子句显示,依此类推,首先以某种方式,我需要解决这两个问题,之后计划是与大约10个queires混合。谢谢P.s中的一个问题,结果的所有内容都显示在列i_di1.naziv

SELECT bolnickiracun.id,
         bolnickiracun.id_dijagnoza1, i_di1.naziv naziv_dijagnoza1
FROM     bolnickiracun
LEFT JOIN i_dijagnoze_marko i_di1 ON bolnickiracun.id_dijagnoza1=i_di1.id
WHERE  bolnickiracun.id_dijagnoza1!="" and i_di1.naziv is null
UNION ALL
SELECT bolnickiracun.id,
         bolnickiracun.id_dijagnoza2, i_di2.naziv naziv_dijagnoza2
FROM     bolnickiracun
LEFT JOIN i_dijagnoze_marko i_di2 ON bolnickiracun.id_dijagnoza2=i_di2.id
WHERE  bolnickiracun.id_dijagnoza2!="" and i_di2.naziv is null

我希望结果看起来像这样:

id id_dijagnoza1   naziv_dijagnoza1   id_dijagnoza2   naziv_dijagnoza2
1     some data         null             
2     some data         null
3                                        some data         null
4                                        some data         null

指向找到naziv_dijagnoza1或naziv_dijagnoza2,其中为null,即,外键显示不存在主键,或者某人导入不存在作为主键的错误外键。

1 个答案:

答案 0 :(得分:0)

这个3 SELECT的示例(第三个通过基于可以看到的模式进行推导预测)应该有助于理解您对10 SELECT的整个查询需要做什么。您需要在每个NULL中不需要的SELECT子句后的每一列填充SELECT

SELECT bolnickiracun.id, bolnickiracun.id_dijagnoza1, i_di1.naziv naziv_dijagnoza1, NULL, NULL, NULL, NULL -- and so on
FROM     bolnickiracun
LEFT JOIN i_dijagnoze_marko i_di1 ON bolnickiracun.id_dijagnoza1=i_di1.id
WHERE  bolnickiracun.id_dijagnoza1!="" and i_di1.naziv is null

UNION ALL

SELECT bolnickiracun.id, NULL, NULL, bolnickiracun.id_dijagnoza2, i_di2.naziv naziv_dijagnoza2, NULL, NULL -- and so on
FROM     bolnickiracun
LEFT JOIN i_dijagnoze_marko i_di2 ON bolnickiracun.id_dijagnoza2=i_di2.id
WHERE  bolnickiracun.id_dijagnoza2!="" and i_di2.naziv is null

UNION ALL

SELECT bolnickiracun.id, NULL, NULL, NULL, NULL, bolnickiracun.id_dijagnoza3, i_di3.naziv naziv_dijagnoza3 -- and so on
FROM     bolnickiracun
LEFT JOIN i_dijagnoze_marko i_di3 ON bolnickiracun.id_dijagnoza3=i_di3.id
WHERE  bolnickiracun.id_dijagnoza3!="" and i_di3.naziv is null

每个SELECT中的列数应该相同,正如您所看到的,对于3 SELECT s,它是7列(每个表2个连接x 3 SELECT s + 1带ID的第一列)。对于10 SELECT s,每个SELECT子句中将有21列(1代表id,2代表每个表,其余代表NULL s)。 不是很好的解决方案,但可能只有数据库结构。

因此对于10 SELECT来说,首先应该是这样的:

    SELECT bolnickiracun.id, bolnickiracun.id_dijagnoza1, i_di1.naziv naziv_dijagnoza1, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
FROM     bolnickiracun
LEFT JOIN i_dijagnoze_marko i_di1 ON bolnickiracun.id_dijagnoza1=i_di1.id
WHERE  bolnickiracun.id_dijagnoza1!="" and i_di1.naziv is null

UNION ALL
...
UNION ALL

SELECT bolnickiracun.id, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, bolnickiracun.id_dijagnoza10, i_di10.naziv naziv_dijagnoza10
FROM     bolnickiracun
LEFT JOIN i_dijagnoze_marko i_di10 ON bolnickiracun.id_dijagnoza10=i_di10.id
WHERE  bolnickiracun.id_dijagnoza10!="" and i_di10.naziv is null