【问题标题】:MySQL CONCAT values on SELF JOINSELF JOIN 上的 MySQL CONCAT 值
【发布时间】:2021-03-02 05:12:56
【问题描述】:

我正在查询我网站上的 ajax 自动建议功能,需要一些帮助。

我正在使用以下查询:

SELECT
    CONCAT(b.cat_name, ' > ', a.cat_name) as value,
    a.cat_id as data

FROM categories a 

LEFT JOIN categories b 
    ON b.cat_id = a.cat_parent_id 

    WHERE a.cat_path LIKE '%health%' OR a.cat_slug LIKE '%health%' OR a.cat_name LIKE '%health%' OR a.cat_legacy_path LIKE '%health%'

ORDER BY a.cat_path ASC LIMIT 500

问题在于 parent_cat_id 为 NULL 的根类别

我仍然希望它们出现在我的结果中,但就目前而言,根类别的结果为空。

有人可以帮我调整这个查询,以便我可以完成我想做的事情吗?

如果我用 CodeIgniter 3 来做这件事有什么不同,那么这里是我在查询中使用的实际活动记录代码:

$search_term = strtolower($search_term);
$this->db->select("CONCAT(b.cat_name, ' > ', a.cat_name) as value, a.cat_id as data");
$this->db->from('categories a');
$this->db->like('a.cat_path', $search_term, 'both', false);
$this->db->or_like('a.cat_slug', $search_term, 'both', false);
$this->db->or_like('a.cat_name', $search_term, 'both', false);
$this->db->or_like('a.cat_legacy_path', $search_term, 'both', false);
$this->db->join('categories b', 'b.cat_id = a.cat_parent_id', 'left');
$this->db->order_by("a.cat_path", 'ASC');
$this->db->limit('500');
$query = $this->db->get(); 

理想情况下,我希望将根类别(其中 cat_parent_id 为 NULL)选为 a.cat_name as value,而不是 CONCAT(b.cat_name, ' > ', a.cat_name) as value

任何帮助将不胜感激。

【问题讨论】:

    标签: mysql codeigniter join


    【解决方案1】:

    你只需要让它有条件:

    SELECT
        COALECSE(CONCAT(b.cat_name, ' > ', a.cat_name), a.cat_name) as value,
    

    或者,更精确地检查 NULL 的确切原因,

    SELECT
        IF(a.cat_parent_id IS NULL, a.cat_name, CONCAT(b.cat_name, ' > ', a.cat_name)) as value,
    

    所以在你的情况下,在 codeigniter 中,它会转化为:

        $this->db->select("COALECSE(CONCAT(b.cat_name, ' > ', a.cat_name), a.cat_name) as value, a.cat_id as data");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-22
      • 2016-03-06
      • 1970-01-01
      • 1970-01-01
      • 2015-06-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多