【问题标题】:Preference in Mysql resultsetMysql 结果集中的首选项
【发布时间】:2019-10-18 09:50:52
【问题描述】:

在 Mysql 中执行以下查询时,我得到了多条记录。

SELECT * 
  FROM catalog_product_entity_int 
 WHERE attribute_id = 99 
   and row_id = 378050

+----------+--------------+----------+--------+-------+
| value_id | attribute_id | store_id | row_id | value |
+----------+--------------+----------+--------+-------+
| 12101931 |           99 |        0 | 378050 |     4 |
| 21858725 |           99 |        3 | 378050 |     1 |
| 21861516 |           99 |        4 | 378050 |     1 |
+----------+--------------+----------+--------+-------+

我需要一个查询来获取 store_id 3 的值,如果 store_id 3 不存在,那么 store_id 0 的值。

【问题讨论】:

  • 如果商店 id 不存在,作为(不)在您的示例数据中?符合您的选择标准的样本数据会很有帮助。
  • 我已经更新了我的问题。

标签: mysql magento magento2


【解决方案1】:

请试试这个

SELECT 
IF((SELECT Count(*) FROm catalog_product_entity_int WHERE store_id = 3) > 0,value ,
IF((SELECT Count(*) FROm catalog_product_entity_int  WHERE store_id = 0) > 0,value ,0)) value
  FROM catalog_product_entity_int 
 WHERE attribute_id = 99 
   and row_id = 378050
 GROUP BY row_id 

如果您选择的行中有这样的行,这将首先选择 store_id 3 的值。 然后它会尝试获取 store_id 0 的值,如果也失败,则值为 0

您必须检查的最后一部分,您将如何检测到您的选择中既没有 store_id 3 也没有 store_id 0。

应该控制 group by 子句。最终 attribute_id 可能会更好

【讨论】:

  • 给出相同的结果。
  • 我添加了一个 Group by,这样你只会得到一行。
【解决方案2】:

获取最大 store_id 并加入源

drop table if exists t;
create table t
( value_id int, attribute_id int, store_id int, row_id int, value int);
insert into t values
( 12101931 ,           99 ,        0 , 378050 ,     4 ),
( 21858725 ,           99 ,        3 , 378050 ,     1 ),
( 21861516 ,           99 ,        4 , 378050 ,     1 ),
( 12101931 ,           99 ,        0 , 378051 ,     4 ),
( 21858725 ,           99 ,        5 , 378051 ,     1 ),
( 21861516 ,           99 ,        4 , 378051 ,     1 ),
( 12101931 ,           99 ,        1 , 378052 ,     4 ),
( 21858725 ,           99 ,        5 , 378052 ,     1 ),
( 21861516 ,           99 ,        4 , 378052 ,     1 ),
( 21861516 ,           99 ,        4 , 378053 ,     1 );


select t.* 
from t
join (select attribute_id, row_id, max(store_id) maxstore
        from t 
        where attribute_id = 99 and store_id in(0,3)
        group by  attribute_id, row_id) s 
        on s.attribute_id = t.attribute_id and s.row_id = t.row_id and s.maxstore = t.store_id;

+----------+--------------+----------+--------+-------+
| value_id | attribute_id | store_id | row_id | value |
+----------+--------------+----------+--------+-------+
| 21858725 |           99 |        3 | 378050 |     1 |
| 12101931 |           99 |        0 | 378051 |     4 |
+----------+--------------+----------+--------+-------+
2 rows in set (0.00 sec)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多