【问题标题】:Check 2 values in 2 columns in a join query在连接查询中检查 2 列中的 2 个值
【发布时间】:2017-06-30 09:57:06
【问题描述】:

我有两张桌子:

prd_brand

  • brand_id
  • 姓名

catalog_product_entity_int

  • attribute_id
  • 行标识
  • 价值

我加入这两个表如下:

SELECT main_table.* 
FROM prd_brand AS main_table 
INNER JOIN catalog_product_entity_int 
ON main_table.brand_id=catalog_product_entity_int.value 
group by brand_id 
order by name asc

我现在要做的是检查catalog_product_entity_int 表,如果attribute_id 97 有value 1。如果它的值不是 1,则不要取它。

prd_brand

brand_id    |   name
26          |   Nivea
44          |   Ducray

catalog_product_entity_int

attribute_id    |   rowid   |   value 
198             |   174     |   26 
97              |   174     |   1
788             |   174     |   4
198             |   210     |   44
97              |   210     |   0

Nivea (ID 26) 存在于catalog_product_entity_int 表中,它的rowid 是174,这个rowid 在attribute_id 97 中有一个值1 => 我们接受它。

Ducray (ID 44) 存在于catalog_product_entity_int 表中,它的rowid 是210,这个rowid 在attribute_id 97 中的值为0 => 我们不接受它。

【问题讨论】:

  • 发布一些示例数据和您的预期结果。
  • 1) 使用select * 和group by 查询是错误的。 2)具有预期输出的样本数据会有所帮助
  • @Forward : 请查看编辑后的示例
  • @OtoShavadze : 请参阅编辑后的示例

标签: mysql join where-clause


【解决方案1】:

这里我用group_concat 和find_in_set 搞定:

select distinct a.*
from prd_brand a
join (
    select
        group_concat(attribute_id order by attribute_id) attrs, 
        group_concat(`value` order by attribute_id) vals
    from catalog_product_entity_int
    group by `rowid`
) b
on find_in_set(a.brand_id, b.vals)
and find_in_set('97', b.attrs) > 0
and find_in_set('1', b.vals);

在此处查看demo。

或join 带有子查询的解决方案:

select distinct a.*
from prd_brand a
join catalog_product_entity_int b1
on a.brand_id = b1.`value`
and exists (
    select 1
    from catalog_product_entity_int b2
    where b1.rowid = b2.rowid
    and b2.`value` = 1
    and b2.`attribute_id` = 97
)

这里也是demo。

【讨论】:

  • 感谢您的解释、演示和两种可能的解决方案!我选择了你的第二个。
【解决方案2】:

一种可能的方法

select prd_brand.* from prd_brand
inner join
(
    select distinct value from catalog_product_entity_int
    where 
    rowid in (select rowid from catalog_product_entity_int where attribute_id = 97 and value = 1)
)t
on prd_brand.brand_id = t.value

【讨论】:

  • 我愿意接受您的回答,因为坦率地说,这是最明确的回答。当然,它有效!谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-01
  • 1970-01-01
  • 2015-01-27
  • 2020-09-16
  • 1970-01-01
  • 2023-03-10
  • 2013-03-03
相关资源
最近更新 更多