需要帮助构建SQL查询

时间:2015-04-08 05:36:01

标签: mysql sql build

我有两张中继表:

Fields: ID(prim. key), Title
Values: ID(prim. key), Value, field_id(for. key)

简单来说,我有很多字段,而每个字段可以包含多个值。

我需要SQL查询来选择值不等于给定值的所有字段。

样品:

Assuming I have two fields:
- fld1 { 1,2,5 }
- fld2 { 1,4 }
I need to get fld1 while looking for fields whose value is NOT equal to 4.

2 个答案:

答案 0 :(得分:1)

这样的东西?还是我完全误解了你?

select *
  from Fields f
    inner join `Values` v
      on f.id = v.field_id
    where v.value <> 4;

答案 1 :(得分:1)

SELECT title 
FROM `Fields` f
WHERE NOT EXISTS (SELECT 1 
                 FROM `Values` v
                 WHERE f.id = v.field_id 
                       AND v.`value` = 4);

SQL Fiddle