我有这样的mysql表
我有2个变量/值,例如FLASH
和LCD
我想:如果FLASH
列中不存在name
,则SELECT ... WHERE
列name = '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
答案 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