一直在做一些MySQL的东西,发现一个棘手的情况需要解决。
这是2个MySQL表
import numpy as np
from sklearn import preprocessing
input_data = np.array([[5.1, -2.9, 3.3],
[-1.2, 7.8, -6.1],
[3.9, 0.4, 2.1],
[7.3, -9.9, -4.5]])
# Binarize data
data_binarized = preprocessing.Binarizer(threshold=2.1).transform(input_data)
print("\nBinarized data:\n", data_binarized)
我正在尝试查找与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
为0,则将brand_id
与keyword
p_name
> 0和brand_id
然后在两个条件下加入keyword != ''
> 0和brand_id
然后加入keyword == ''
总的来说,我需要查找与brand_id and p_brand
行匹配的产品数量。
尝试过此查询,但确实只包含一个条件:
user_fav
有任何解决此问题的建议吗?
谢谢!
答案 0 :(得分:2)
<强> SQL DEMO 强>
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 |
答案 1 :(得分:0)
您的加入条件并非一对一,因此您可以对条件进行分组,因为每个规则集都不包含下一个规则集。
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`