簡體   English   中英

通過可選的列匹配連接2個表

[英]Join 2 tables with optional column match

已經做了一些MySQL的工作,發現了一個棘手的情況需要解決。

這是2個MySQL表

Table1: user_fav

fav_id | brand_id | Keyword
   1   |    0     | test
   2   |    67    | test1
   3   |    68    |


Table 2: products

p_id   | p_brand |   p_name
  1    |   67    | test1 shoes
  2    |   68    | test shoes

我正在嘗試找到與user_fav表匹配的產品數,如下所示:

  • 如果brand_id為0,則將keywordp_name匹配
  • 如果brand_id > 0且keyword != ''則同時滿足這兩個條件
  • 如果brand_id > 0且keyword == ''則加入brand_id and p_brand

總體而言,我需要查找與user_fav行匹配的產品數。

嘗試過此查詢,但它僅包含一個條件:

select `uf`.`fav_id`, count(`p`.`p_id`) AS `pcount` from (`user_fav` `uf` left join `products` `p` on(((`p`.`p_name` like convert(concat('%',`uf`.`keyword`,'%') using utf8))))) group by `uf`.`fav_id`

有什么建議可以解決這個問題嗎?

謝謝!

SQL演示

SELECT u.*, count(p.p_id) as pcount
FROM user_fav u
JOIN products p
  ON ( u.`brand_id` = 0 and p.`p_name` Like CONCAT('%',  u.`Keyword`, '%'))
  OR ( u.`Keyword` = '' and u.`brand_id` = p.`p_brand`)  
  OR (  u.`brand_id` > 0 and u.`Keyword` <> '' and 
        ( u.`brand_id` = p.`p_brand` AND p.`p_name` Like CONCAT('%',  u.`Keyword`, '%'))
      ) group by u.fav_id

輸出值

| fav_id | brand_id | Keyword | pcount |
|--------|----------|---------|--------|
|      1 |        0 |    test |      2 |
|      2 |       67 |   test1 |      1 |
|      3 |       68 |         |      1 |

您的加入條件不僅是一對一的,因此您可以對條件進行分組,因為每個規則集都不包含下一個規則集。

select 
    `uf`.`fav_id`, 
    count(`p`.`p_id`) AS `pcount` 
from 
    `user_fav` `uf` 
left join 
    `products` `p` 
    ON (
       `uf`.`brand_id` = 0
       AND `uf`.`Keyword` = `p`.`p_name`
    )
    OR (
        `uf`.`brand_id` > 0
       AND `uf`.`Keyword` != ''
       AND `uf`.`Keyword` = `p`.`p_name`
       AND `uf`.`brand_id` = `p`.`p_id`
    )
    OR (
        `uf`.`brand_id` > 0
       AND `uf`.`Keyword` = ''
       AND `uf`.`brand_id` = `p`.`p_id`
    )
group by `uf`.`fav_id`

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM