合并SELECT查询和SELECT COUNT查询

时间:2017-04-20 13:05:54

标签: php mysql

我在MySql中有一个表(关联),具有唯一和重复的键:

id | key
 1 | a
 2 | b
 3 | b
 4 | c
 5 | d
 6 | d

我有一个产品表(产品):

id | product  | type
 1 | product1 | one
 2 | product2 | one
 3 | product3 | two
 4 | product4 | two
 5 | product5 | two
 6 | product6 | two

现在我只关注关联中唯一的产品并键入'two',以便我通过此查询得到这些ID:

SELECT assoc.id, count(*)
FROM __associations assoc
GROUP BY assoc.key
HAVING COUNT(*) <= 1

返回ID 1和4以及

SELECT prod.id, prod.product, prod.type
FROM __products prod
WHERE prod.type = two

返回3,4,5和6

但我尝试将这两个查询合并并获得ID 4都失败了:(

3 个答案:

答案 0 :(得分:1)

此查询应该为您提供正确的结果:

SELECT prod.id, prod.product, prod.type
FROM __products prod
WHERE prod.type = two and prod.id in (SELECT assoc.id    
  FROM __associations assoc
  GROUP BY assoc.key
  HAVING COUNT(*) <= 1)

答案 1 :(得分:0)

试试这个:

SELECT assoc.id, count(*)
FROM __associations assoc
JOIN __products prod ON assoc.id = prod.id
GROUP BY assoc.key
HAVING COUNT(*) <= 1 AND 
       COUNT(CASE WHEN prod.type = 'two' THEN 1 END) > 0

该查询在其HAVING子句中使用条件聚合,以过滤掉与{em>至少一个无关的assoc.key个组products记录type = 'two'

答案 2 :(得分:0)

您需要从多个表中进行选择。

  

SELECT table1.column1,table2.column2 FROM table1,table2 WHERE table1.column1 = table2.column1;

SQL basics: Query multiple tables

15:53:41.510722 IP (tos 0x0, ttl 248, id 18315, offset 0, flags [none], proto TCP (6), length 123) XXX.XXX.XXX.XXX.80 > XXX.XXX.XXX.XXX.53618: Flags [F.], cksum 0xb96f (correct), seq 85:168, ack 1, win 5840, length 83: HTTP, length: 83 HTTP/1.1 302 Moved Temporarily Location: http://XXX.XXX.XXX.XXX Connection: close