如何从另一个表获取值

时间:2018-10-30 16:56:01

标签: mysql

我有2个表“ srot_data”和“ vada”

CREATE TABLE `srot_data` (`ID` int(10) NOT NULL,Datum` datetime DEFAULT NULL,`ID_obsluha` int(10) DEFAULT NULL,`Linka` varchar(10) DEFAULT NULL,`Kontejner` varchar(10) DEFAULT NULL,`Vada` int(10) DEFAULT NULL,`m_srot` decimal(8,3) DEFAULT NULL,`m_pres` decimal(8,3) DEFAULT NULL,`blok` int(10) DEFAULT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `vada` (`ID` int(10) NOT NULL,`Cislo` int(10) DEFAULT NULL,`Popis` varchar(50) DEFAULT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8;

样本数据:

INSERT INTO `srot_data` (`ID`, `Datum`, `ID_obsluha`, `Linka`, `Kontejner`, `Vada`, `m_srot`, `m_pres`, `blok`) VALUES(1, '2018-04-16 11:23:44', 21, 'EXMET2', 'ELDY-', 18, '27.500', '12.500', 1),
INSERT INTO `vada` (`ID`, `Cislo`, `Popis`) VALUES(1, 1, 'Najíždění výroby(resp. nové elektrody)'),(2, 2, 'Expander - poškozená mřížka'),(3, 3, 'Olověný pás - koroze '),(4, 4, 'Olověný pás - potrhaná mřížka'),(5, 5, 'Pastovačka - nedopastované elektrody'),(6, 6, 'Pastovačka - nerovnoměrné pastování (křivé stohy)'),

我需要获得:

  {"Total":"37", "vada":"Pastovačka - nedopastované elektrody".}

但这就是我现在得到的

{"Total":"37", "vada":"5".}

我的sql是:

$sql = "SELECT count(blok) AS Total , 
           Vada AS vada 
    FROM srot_data 
    LEFT JOIN vada ON vada.Popis = srot_data.Vada 
    WHERE Linka = 'EXMET1' 
    GROUP BY vada 
    ORDER BY Total DESC limit 1";

“ vada”:“Pastovačka-nedopastovanéelektrody”是表vada中的Popis,其表srot_data中的数字为5。

如何获取值而不是数字?

1 个答案:

答案 0 :(得分:0)

  1. 您应该选择Popis列。
  2. 您所说的“加入”列是错误的。应该是LEFT JOIN vada ON vada.Vada = srot_data.Vada

    $sql = "SELECT count(blok) AS Total ,   
           Popis AS vada   
           FROM srot_data   
           LEFT JOIN vada ON vada.Id = srot_data.Vada   
           WHERE Linka = 'EXMET1'  
           GROUP BY vada  
           ORDER BY Total DESC limit 1";