mysql SELECT。如果WHERE中的值不存在,那么SELECT基于另一个(值)WHERE

时间:2014-11-06 06:36:59

标签: mysql

我有这样的mysql表

CategoryForTest table

我有2个变量/值,例如FLASHLCD

我想:如果FLASH列中不存在name,则SELECT ... WHEREname = 'LCD'。如果存在FLASH,则不会根据LCD

进行选择

写了这样的查询

SELECT 

t1.name AS lev1, t1.url AS url1

FROM CategoryForTest AS t1
LEFT JOIN CategoryForTest AS t2 ON t2.parent = t1.category_id
LEFT JOIN CategoryForTest AS t3 ON t3.parent = t2.category_id
LEFT JOIN CategoryForTest AS t4 ON t4.parent = t3.category_id

WHERE exists (
SELECT name
from CategoryForTest
WHERE t4.name = 'FLASH'
)

UNION ALL

SELECT 

t1.name AS lev1, t1.url AS url1

FROM CategoryForTest AS t1
LEFT JOIN CategoryForTest AS t2 ON t2.parent = t1.category_id
LEFT JOIN CategoryForTest AS t3 ON t3.parent = t2.category_id
LEFT JOIN CategoryForTest AS t4 ON t4.parent = t3.category_id

WHERE not exists (
SELECT name
from CategoryForTest
WHERE t4.name = 'FLASH'
)
AND t2.name = 'LCD'

但是我得到了

Array
(
[0] => Array
    (
        [lev1] => ELECTRONICS
        [url1] => url-electronics
    )

[1] => Array
    (
        [lev1] => TELEVISIONS
        [url1] => url-televisions
    )

)

期待只见[0] => Array

2 个答案:

答案 0 :(得分:1)

这可能会对你有帮助。

(
   SELECT 

     t1.name AS lev1, t1.url AS url1

   FROM test AS t1
     LEFT JOIN test AS t2 ON t2.parent = t1.categ_id
     LEFT JOIN test AS t3 ON t3.parent = t2.categ_id
     LEFT JOIN test AS t4 ON t4.parent = t3.categ_id

   WHERE not exists (
       SELECT 

         t1.name AS lev1, t1.url AS url1

       FROM test AS t1
         LEFT JOIN test AS t2 ON t2.parent = t1.categ_id
         LEFT JOIN test AS t3 ON t3.parent = t2.categ_id
         LEFT JOIN test AS t4 ON t4.parent = t3.categ_id

      WHERE exists (
         SELECT name
         from test
         WHERE t4.name = 'FLASH'
      )
   )
   AND t2.name = 'LCD'
 GROUP BY t1.categ_id
)
UNION ALL
(
   SELECT 

     t1.name AS lev1, t1.url AS url1

   FROM test AS t1
     LEFT JOIN test AS t2 ON t2.parent = t1.categ_id
     LEFT JOIN test AS t3 ON t3.parent = t2.categ_id
     LEFT JOIN test AS t4 ON t4.parent = t3.categ_id

   WHERE exists (
     SELECT name
     from test
     WHERE t4.name = 'FLASH'
   )
)

fidle是here

答案 1 :(得分:0)

根据此https://stackoverflow.com/a/8354045/2118559

找到解决方案
SELECT 

t1.name AS lev1, t2.name as lev2, t3.name as lev3, t4.name as lev4,
t1.url AS url1, t2.url as url2, t3.url as url3, t4.url as url4

FROM CategoryForTest AS t1
LEFT JOIN CategoryForTest AS t2 ON t2.parent = t1.category_id
LEFT JOIN CategoryForTest AS t3 ON t3.parent = t2.category_id
LEFT JOIN CategoryForTest AS t4 ON t4.parent = t3.category_id

WHERE t4.name = 'FLASH' OR t2.name = 'LCD'
LIMIT 1

如果存在FLASH,则根据FLASH获取数据。如果FLASH不存在,则根据LCD

进行提取