【问题标题】:Composite key, in comparison复合键,比较
【发布时间】:2015-05-06 16:05:08
【问题描述】:

我有三个字段构成表上的唯一复合键。

我想传入索引匹配的 3 个不同的数组。

custIds= [0,1,2]
custLetters = [A,B,C]
products = ["Cheese","lemons","Aubergine"]

是否有一条 sql 语句将返回所有三行(假设它们存在), 由于“误报”,仅通过 in 组合将不起作用:

select * from mytable 
where custId in (custIds)
 and custLetters in (custLetters)
and product in (products);

数据库oracle,但是通过hibernate hql,所以如果可能的话首选ansi?

【问题讨论】:

  • 如果您愿意,可以使用hibernate criteria

标签: java sql oracle hql


【解决方案1】:

OT:您的 SQL 查询可能是错误的。应该是:

select * from mytable 
where (custId, custLetters, product) 
in ( (0, 'A', 'Cheese'),
 (1, 'B', 'lemons'),
 (2, 'C', 'Aubergine'));

我不使用 Hibernate 是否可以生成这样的查询。但是in 只是结合和析取的语法糖。

【讨论】:

  • Hibernate HQL 与 SQL 查询相同。
  • @AfsunKhammadli 它是相似的,但有很多不同之处。绝对不一样。
【解决方案2】:

之后,您可以将数组组合成一个数组:

custIds= [0,1,2]
custLetters = [A,B,C]
products = ["Cheese","lemons","Aubergine"]

Key=["0ACheese","1Blemons","2CAubergine"]

select * from mytable 
where custId+custLetters+product in (Key);

【讨论】:

  • 如果存在 custid = 1、custletter = A 和 products = lemons 的现有记录,这将如何工作?
  • @DanBrauck 不会,但这不是问题所在。一个相当老套的解决方案,但可以工作 +1
  • 不行,因为custId+custLetters+product 是无效的 SQL。字符的连接运算符是 || + 符号是数字。
猜你喜欢
  • 2015-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-13
  • 1970-01-01
  • 2022-01-13
  • 1970-01-01
相关资源
最近更新 更多