PHP MySQL Group BY有问题

时间:2017-03-29 20:10:40

标签: php mysql where having

假设我有一个像这样的表:

ID|Word |Reference
1 |Dog  |1
1 |Fish |2
1 |Sheep|3
2 |Dog  |4
2 |Fish |5
3 |Sheep|6
4 |Dog  |7

我想选择所有包含单词Dog AND Sheep的ID。所以结果应该是ID:1和2.我尝试使用这个查询:

SELECT ID FROM `Table` WHERE Word='Dog' OR Word='Fish' GROUP BY ID Having Word='Dog AND Word='Fish'

但是,AND子句中的Having使我得到0结果。所以,我做错了什么或者是否有另一种方法来实现我想要的基于MySQL查询的扫描(为了优化速度,因为它必须使用与上例相同的设置搜索许多行)

基本上问题是具有相同ID的多行的AND语句。

更新:
我需要获取找到的ID的引用。例如。返回ID 1和2时,我需要知道ID 1有引用1和2. ID 2有引用3和4.目前,我正在使用此查询:

SELECT ID FROM `Test` WHERE Word in ('Dog', 'Fish') GROUP BY ID HAVING  count(DISTINCT Word) = 2;

由于

4 个答案:

答案 0 :(得分:1)

以下是两个返回正确记录的解决方案,第一个是ID和参考的单个记录,第二个是每个ID一个记录,单词和参考以逗号分隔列。

设置表并填充行:

DROP TABLE IF EXISTS `list1`;

CREATE table `list1` (
    id int(10),
    Word varchar(10),
    Reference int(10) 
);

INSERT INTO `list1` (`ID`, `Word`, `Reference`) 
VALUES 
(1, 'Dog',1),
(1 ,'Fish',2),
(1 ,'Sheep',3),
(2 ,'Dog',4),
(2 ,'Sheep',5),
(3 ,'Sheep',6),
(4 ,'Dog',7);

为ID和Word的每个组合返回一行

SELECT 
    t.`ID`,
    t.`Word`,
    t.`Reference`
FROM `list1` as t
JOIN (
    SELECT 
        t1.`ID` as `ref_id`
    FROM `list1` AS t1
    WHERE `Word` in ('Sheep','Dog')
    GROUP BY t1.`ID`
    HAVING count(DISTINCT t1.`Word`) = 2
) AS ts
ON t.`ID` = ts.`ref_id`
WHERE t.`Word` in ('Sheep','Dog')
ORDER BY t.`ID`,t.`Word`;

<强>结果

ID  |   Word    |   Reference   
1   |   Dog     |   1
1   |   Sheep   |   3
2   |   Dog     |   4
2   |   Sheep   |   5

每个ID返回一行,在一列中使用逗号分隔的单词列表,在另一列中以逗号分隔的Reference列表。

SELECT 
    t.`ID`,
    GROUP_CONCAT(t.`Word`) AS `Words`,
    GROUP_CONCAT(t.`Reference`) AS `References`
FROM `list1` as t
JOIN (
    SELECT 
        t1.`ID` as `ref_id`
    FROM `list1` AS t1
    WHERE `Word` in ('Sheep','Dog')
    GROUP BY t1.`ID`
    HAVING count(DISTINCT t1.`Word`) = 2
) AS ts
ON t.`ID` = ts.`ref_id`
WHERE t.`Word` in ('Sheep','Dog')
GROUP BY t.`ID`
ORDER BY t.`ID`,t.`Word`;

<强>结果:

ID  |   Words       |   References  
1   |   Dog,Sheep   |   1,3
2   |   Dog,Sheep   |   4,5

答案 1 :(得分:0)

您需要自己加入表格。通过这种方式,您可以在狗和羊重叠的情况下获取id相同的位置。 试试这个:

declare @t table (id int ,  Word varchar(10) )
insert into @t (ID, Word) values (1, 'Dog'),
(1 ,'Fish'),
(1 ,'Sheep'),
(2 ,'Dog'),
(2 ,'Sheep'),
(3 ,'Sheep'),
(4 ,'Dog')

select t.ID
from @t as t
join @t as t1 on t1.id = t.id
where t.word = 'Dog' and t1.word = 'Sheep'

答案 2 :(得分:0)

这是通过将您的桌子加入自身来实现这一目标的一种方式。

SELECT t1.id FROM `Table` t1
INNER JOIN `Table` t2 ON t1.id = t2.id
WHERE t1.word='Dog' AND t2.word='Sheep';

答案 3 :(得分:0)

使用下面的查询解决了我的问题的答案:

SELECT ID, GROUP_CONCAT(Reference) as ReferencesGrouped FROM `Test` WHERE Word in ('Dog', 'Fish') GROUP BY ID HAVING  count(DISTINCT Word) = 2;

这会让我回复:

ID|ReferencesGrouped
1 |1,4
2 |4,5