【问题标题】:sql join with multiple conditions on columnssql join 与列上的多个条件
【发布时间】:2022-01-03 06:02:54
【问题描述】:

我认为我无法通过工会实现这一目标。 例如,我想要所有关键列是“品牌”且价值列是“Burago”的汽车。 最重要的是,键列价格在 100 到 220 之间。

我应该做子查询还是什么?如果我也想查询值为“sport”的键“type”怎么办? 该查询仅在我使用一个 where 子句时返回某些内容,而在使用以下查询时不返回任何内容。

select `posts`.`title` from `posts`
  inner join `meta` on `posts`.`id` = `meta`.`metable_id`
  where `meta`.`key` = "price" and `meta`.`value` between 100 and 220
   and `meta`.`key` = "brand" and `meta`.`value` = "Burago"
 group by `posts`.`id`

元表:

ID  | post_id |   key     |       value
----------------------------------------------------
69  |   8     |   brand   | some-brand
----------------------------------------------------
70  |   8     |   type    | sport
----------------------------------------------------
70  |   8     |   price   | 100
----------------------------------------------------
71  |   8     |   brand   | some-other-brand
----------------------------------------------------
70  |   8     |   type    | coupe
----------------------------------------------------
72  |   8     |   price   | 150
----------------------------------------------------
73  |   8     |   brand   | some-brand
----------------------------------------------------
70  |   8     |   type    | cabrio
----------------------------------------------------
74  |   8     |   price   | 100
----------------------------------------------------
75  |   8     |   brand   | some-brand
----------------------------------------------------
70  |   8     |   type    | sport
----------------------------------------------------
76  |   8     |   price   | 250

【问题讨论】:

  • 样本数据很好,但您还需要指定预期结果。以及其他表的数据。即minimal reproducible example.
  • 请注意,'2' > '100'。
  • 最近有人问过类似的question

标签: sql laravel join eloquent


【解决方案1】:
select `posts`.`title` from `posts`
  inner join `meta` on `posts`.`id` = `meta`.`metable_id`
  where `meta`.`key` = "price" and `meta`.`value` between 100 and 220
   and `meta`.`key` = "brand" and `meta`.`value` = "Burago"
 group by `posts`.`id`
having COUNT(DISTINCT `meta`.`key`) = 2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-12
    • 1970-01-01
    • 2016-12-20
    • 2019-09-01
    • 2021-11-21
    • 2017-02-20
    • 2014-10-04
    • 2012-06-20
    相关资源
    最近更新 更多