选择两个表并在一个表中查看

时间:2019-02-27 12:01:43

标签: php html select mysqli

我有一张桌子旁边的BD。

TABLE detalle_contrato

enter image description here

TABLE detalle_tradicional

enter image description here

ID_CONTRATO有关系,我需要查看下一个数据表。

SELECT
    ID_CONTRATO,
    TRADICIONAL,
    NOM_VARIEDAD,
    SUM(CANTIDAD)
FROM detalle_contrato
WHERE ID_CONTRATO = '$ID' AND TIPO_VARIEDAD = 'TRADICIONAL';

SELECT
    SUM(CANTIDAD_D)
FROM detalle_tradicional
WHERE ID_CONTRATO = '$ID'
GROUP BY NOM_VARIEDAD ";

这两个选择有一个不同的过滤器,我需要在表中使用它,但我不知道。

想法是这样的:

ID_CONTRATO, 
NOM_VARIEDAD, 
CANTIDAD
    ( THIS IS THE SUM THE ALL CANTIDAD DUKE AND 
      LEGACY IN GROUP THE TABLE DETALLE_CONTRATO) ,
CANTIDAD_D
    (TABLE DETALLE_TRADICIONAL THIS IS SUM 
    THE ALL DUKE AND LEGACY SEPARATE THE CANTIDAD_D

我需要使用照片中的数据

enter image description here

1 个答案:

答案 0 :(得分:1)

You can use LEFT JOIN. Left join your second table with id_contrato and  detalle_contrato id_contrato.



SELECT
    dc.ID_CONTRATO,
    dc.TRADICIONAL,
    dc.NOM_VARIEDAD,
    dc.IFNULL(SUM(CANTIDAD),0) AS CANTIDAD,
    dc.IFNULL(SUM(CANTIDAD_D),0) AS CANTIDAD_D
FROM
    detalle_contrato dc
LEFT JOIN TABLE_NAME t2 ON t2.ID_CONTRATO = dc.ID_CONTRATO
WHERE dc.ID_CONTRATO = '$ID' AND t2.TIPO_VARIEDAD = 'TRADICIONAL'