Php 使用可选的列匹配连接2个表
一直在做一些MySQL的事情,发现了一个棘手的问题需要解决 这里有两个MySQL表Php 使用可选的列匹配连接2个表,php,mysql,Php,Mysql,一直在做一些MySQL的事情,发现了一个棘手的问题需要解决 这里有两个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 |
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\u fav
表匹配的产品数量,如下所示:
- 如果
为0,则将brand\u id
与keyword
p\u name
- 如果
>0和brand\u id
关键字!=''代码>然后在这两种条件下加入
- 如果
>0和brand\u id
则加入keyword=''
brand\u id和p\u brand
用户\u 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`
有什么建议可以解决这个问题吗
谢谢
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
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
您的连接条件不必是一对一的,因此您可以对条件进行分组,因为每个规则集都不包含下一个规则集
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`
您的连接条件不必是一对一的,因此您可以对条件进行分组,因为每个规则集都不包含下一个规则集
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`