从另一个表中的数据中选择表值

时间:2013-05-19 13:39:20

标签: sql select join

我有2张桌子

产品

id | property1 | property2|property3 |category
--------------------------|--------------------
1  | trousers  | red      |UK        |  1
2  | shoes     | blue     |USA       |  2
3  | shoes     | red      |RU        |  1

类别

id | property1 | property2 | property3 
---------------------------------------
1  |    1      |   1       |   0 
2  |    1      |   0       |   1

我需要从PRODUCTS中选择在PRODUCTS中标记为1的值。

SELECT FROM `products` WHERE  category = 1 VALUES id, ... {plus that have been marked as 1 in 'categories'}

我需要结果看起来像

id | property1 | property2 | 
----------------------------
1  | trousers  |   red     |   
3  | shoes     |   red     |   

我不需要额外的数据,否则会破坏我现有的php代码。此查询的目标是数组

[0] =>
      ['id'] => '1'
      ['property1'] => 'trousers'
      ['property2'] => 'red'
[1] =>
      ['id'] => '3'
      ['property1'] => 'shoes'
      ['property2'] => 'red'

单一查询

2 个答案:

答案 0 :(得分:1)

select id,property1,property2 from PRODUCTS where category = 1

答案 1 :(得分:0)

这几乎就是你想要的。它将返回属性不匹配的NULL值。最简单的事情可能是使用它然后在客户端进行解析:

select p.id,
       (case when c.category1 = 1 then p.property1 end) as Property1,
       (case when c.category2 = 1 then p.property2 end) as Property2,
       (case when c.category3 = 1 then p.property3 end) as Property3
from Products p join
     Categories c
     on p.CategoryId = c.CategoryId;

这个版本可以做你想要的,但它更复杂:

select p.id,
       (case when c.category1 = 1 then p.property1
             when c.category1 = 0 and c.category2 = 1 then p.property2
             when c.category1 = 0 and c.category2 = 0 and c.category3 = 1 then p.property3
        end) as Property1,
       (case when c.category1 = 1 and c.category2 = 1 then p.property2
             when (c.category1 = 1 and c.category2 = 0 and c.category3 = 1) or
                  (c.category1 = 0 and c.category2 = 1 and c.category3 = 1)
             then p.property3
        end) as Property2,
       (case when c.category3 = 1 and c.category2 = 1 and c.category1 = 1
             then p.property3 end) as Property3
from Products p join
     Categories c
     on p.CategoryId = c.CategoryId;

如果您有三列以上,那么pivot / unpivot(某些但不是所有数据库都可用)可以帮助简化代码。