在查询之前检查表?

时间:2018-07-23 20:33:39

标签: sql

在以下查询中,如何执行子查询以查找exp_categories中具有parent_id的所有类别以及所有具有父类别但没有任何子类别的类别,然后用这个代替AND c.parent_id != '0'

SELECT c.cat_url_title
FROM exp_channel_titles as t
LEFT JOIN exp_category_posts AS cp ON cp.entry_id = t.entry_id
LEFT JOIN exp_categories AS c ON cp.cat_id = c.cat_id
WHERE t.url_title = 'hummingbird'
AND c.parent_id != '0'
AND c.cat_url_title != 'latest-work'
AND c.cat_url_title != 'best-selling-images' 
LIMIT 1

1 个答案:

答案 0 :(得分:1)

像这样吗?

SELECT c.cat_url_title
FROM exp_channel_titles as t
LEFT JOIN exp_category_posts AS cp ON cp.entry_id = t.entry_id
LEFT JOIN exp_categories AS c ON cp.cat_id = c.cat_id
WHERE t.url_title = 'hummingbird'
AND c.parent_id in (
  select id from exp_categories where parent_id is not null
  union
  select id from exp_categories where id not in (
    select parent_id from exp_categories
    )
)
AND c.cat_url_title != 'latest-work'
AND c.cat_url_title != 'best-selling-images' 
LIMIT 1