在字段中订阅在sql中

时间:2012-03-15 20:38:07

标签: mysql sql

我有一个包含这些字段的表

id,cid,cv

使用这些数据

1,5,code
2,3,code4
3,3,cod2
1,4,code5
1,3,code4

]想要选择id,cid = 5,cv = code,cid = 3或4,cv = code4。 我希望id = 1。 我使用了这个查询,但结果是0

SELECT id FROM table WHERE (cid='5' and cv='code') and (cid in ('3','4') and cv='code4')
抱歉英语不好。

4 个答案:

答案 0 :(得分:3)

SELECT id FROM my_table  
WHERE (cid=5 and cv='code') 
or ((cid = 3 and cv='code4') 
and (cid = 4 and cv='code4')) 
group by id

SQL Fiddle Example

答案 1 :(得分:1)

尝试此操作(将术语之间的AND更改为OR):

SELECT id 
FROM table 
WHERE (cid='5' and cv='code') OR (cid in ('3','4') and cv='code4')

答案 2 :(得分:1)

您应该尝试使用ORs代替ANDs

SELECT id 
FROM table 
WHERE (cid='5' and cv='code') 
    OR (cid in ('3','4') and cv='code4')

答案 3 :(得分:1)

我把它放在http://sqlfiddle.com/#!2/40054/51(你可以告诉我最后一个数字是51,我做了一些错误的转弯)。我认为这被称为" Key Value,"我建议对这篇文章的标签进行编辑,但我认为你应该重新标记它以包含键值。无论如何:与一行引用一个事物的方法相比,这样的数据库很难查询 - 相反,你有一行引用一个属性。所以如果你想知道什么"事情"拥有某些属性,您必须将每个事物的属性粘贴在一行中。运行下面的查询,您将看到我的意思:

SELECT  laptops.laptop, rams.termvalue as ramCount,
  cpus.termvalue as cpusCount, 
  maker.termvalue as company
  FROM  (SELECT DISTINCT laptop FROM my_table) As Laptops

LEFT JOIN (SELECT laptop, termvalue FROM my_table 
            WHERE term = 'ram') AS rams
            ON rams.laptop = laptops.laptop
LEFT JOIN (SELECT laptop, termvalue FROM my_table 
            WHERE term = 'cpu') AS cpus
            ON cpus.laptop = laptops.laptop
LEFT JOIN (SELECT laptop, termvalue FROM my_table 
            WHERE term = 'company') AS maker
            ON maker.laptop = laptops.laptop

如果你提出有关此类数据库的其他问题,你应该总是提到你正在使用"键/值"安排,它不常见,而不是我们任何人所假设的。

在您的小提琴示例中,您希望找到company = dell和cpu = 2或ram = 2,因此您可以通过将其包装在括号中来查询 整个查询给它一个别名,如:

SELECT * FROM  (
SELECT  laptops.laptop, rams.termvalue as ramCount,
  cpus.termvalue as cpusCount, 
  maker.termvalue as company
  FROM  (SELECT DISTINCT laptop FROM my_table) As Laptops

LEFT JOIN (SELECT laptop, termvalue FROM my_table 
            WHERE term = 'ram') AS rams
            ON rams.laptop = laptops.laptop
LEFT JOIN (SELECT laptop, termvalue FROM my_table 
            WHERE term = 'cpu') AS cpus
            ON cpus.laptop = laptops.laptop
LEFT JOIN (SELECT laptop, termvalue FROM my_table 
            WHERE term = 'company') AS maker
            ON maker.laptop = laptops.laptop
) as laps
WHERE  company = 'dell' AND (cpuscount = 2 OR ramcount = 2)