mysql选择问题

时间:2011-03-17 11:32:00

标签: mysql sql

我喜欢跟随表。

我想选择匹配 - > “Tip-1 = 225,Tip-2 = 65,Tip3 = 16”产品。

有1件商品符合查询条件。产品ID 2。

但我不知道怎么办请帮助我。

id  product_id  option_id   name    label   value
44  1                   4   Tip-5   Tip 5   Dört Mevsim
42  1                   2   Tip-2   Tip 2   65
48  2                   4   Tip-5   Tip 5   Dört Mevsim
47  2                   3   Tip-3   Tip 3   16
46  2                   2   Tip-2   Tip 2   65
45  2                   1   Tip-1   Tip 1   225
52  3                   4   Tip-5   Tip 5   Dört Mevsim
51  3                   3   Tip-3   Tip 3   16
50  3                   2   Tip-2   Tip 2   75
49  3                   1   Tip-1   Tip 1   215
60  4                   4   Tip-5   Tip 5   Dört Mevsim
58  4                   2   Tip-2   Tip 2   75
64  5                   4   Tip-5   Tip 5   Dört Mevsim
63  5                   3   Tip-3   Tip 3   12
62  5                   2   Tip-2   Tip 2   85
61  5                   1   Tip-1   Tip 1   155
59  4                   3   Tip-3   Tip 3   16
43  1                   3   Tip-3   Tip 3   16
41  1                   1   Tip-1   Tip 1   205
57  4                   1   Tip-1   Tip 1   205
72  6                   4   Tip-5   Tip 5   Dört Mev

4 个答案:

答案 0 :(得分:3)

试试这个:

SELECT product_id
FROM yourtable
WHERE (name, value) IN (('Tip-1', '225'), ('Tip-2', '65'), ('Tip-3', '16'))
GROUP BY product_id
HAVING COUNT(*) = 3

这假设(product_id,name)是唯一的。如果没有,请改用COUNT(DISTINCT name)

答案 1 :(得分:0)

最好有自己的产品详细信息表,但要选择尝试这个

SELECT * FROM table_name WHERE (name = "Tip-1" AND value = 225) AND (name = "Tip-2" AND value = 65) AND (name = "Tip-3" AND value = 16) GROUP BY product_id

这可能会有效,但桌面结构非常糟糕,如果可能的话,你应该对它进行检查..

答案 2 :(得分:0)

首先,除非您有非常具体的需求,否则这是一个糟糕的数据库设计。那就是说,

SELECT T1.product_id
FROM mytable T1
JOIN mytable T2 ON T1.product_id = T2.product_id
JOIN mytable T3 ON T1.product_id = T3.product_id
WHERE T1.name = 'Tip-1' AND T1.value = '255'
  AND T2.name = 'Tip-2' AND T2.value = '65'
  AND T3.name = 'Tip-3' AND T3.value = '16'

答案 3 :(得分:0)

使用OR子句和HAVING的常规组应该这样做

SELECT   product_id
FROM     yourtable
WHERE    (name = 'Tip-1' and value = '225')
   OR    (name = 'Tip-2' and value = '65')
   OR    (name = 'Tip-3' and value = '16')
GROUP BY product_id
HAVING   COUNT(distinct value) = 3