MySQL条件LEFT JOIN

时间:2016-11-26 18:59:02

标签: php mysql

我有两张表有一对多的关系。地方和促销。一个地方可以有几个促销,适用于星期几。

简化(省略大多数列),这些是表:

放置

idnum   nombre
--
42      SUBWAY
55376   ANTOJERIA MAKECH
50112   TORTAS BERNAL LAS ORIGINALES DESDE 1960
55185   LA MARINERA

促销

idnum   titulo                  dia     idcliente
135     Pescado Frito 2 x 1     Lunes   55185
136     Pescado Frito 2 x 1     Martes  55185
137     Margaritas 2 x 1        Jueves  55185
138     Tacos 3 x 2             Viernes 55185
139     5 cervezas              Sabado  55185

我想构建一个查询,它可以获取所有Place结果,如果可用,我会获得相应的促销。这是我到目前为止的查询:

SELECT * FROM (SELECT d.nombre, a.dia, a.descripcion FROM directorio as d LEFT JOIN avisos as a ON d.idnum = a.idcliente WHERE palabras LIKE "%Marinera%" LIMIT 15 OFFSET 0) AS t WHERE t.dia = "Sabado" OR t.dia IS NULL;

当dia匹配查询时(在这种情况下" Sabado")或dia是NULL(当地方没有促销时),它可以正常工作;但当地方确实有促销但没有一个匹配dia 时会出现问题......在这种情况下,我仍希望在促销列上获得空值的记录。

1 个答案:

答案 0 :(得分:1)

如果您想在dia!=表格“Sabado”时也能得到答案,那么您可以使用CASE WHEN

  SELECT * 
  FROM (
      SELECT d.nombre, case when a.dia = "Sabado"  then a.dia else NULL END, a.descripcion 
      FROM directorio as d 
      LEFT JOIN avisos as a ON d.idnum = a.idcliente 
      WHERE palabras LIKE "%Marinera%" LIMIT 15 OFFSET 0) AS t 
  WHERE t.dia = "Sabado" 
  OR t.dia IS NULL;

这个用max(dia)删除重复的行

  SELECT 
        idnum
      , nombre
      , MAX(dia) as dia
      , descripcion 
  FROM ( 
        SELECT 
              d.idnum
            , d.nombre
            , case when a.dia = "Domingo" then a.dia else NULL END as dia
            , a.descripcion FROM directorio as d 
      LEFT JOIN avisos as a ON d.idnum = a.idcliente 
      WHERE palabras LIKE "%Marinera%"
      LIMIT 15 OFFSET 0) AS t 
  WHERE t.dia = "Domingo" OR t.dia IS NULL