获取所有行具有相同列值的mysql数据

时间:2016-10-21 16:24:28

标签: mysql

我希望获得具有相同部分值的所有行,例如

1. lesson 1 part=1
2. lesson 1.1 part=1
3. lesson 2 part=2

我想得到第1课和第1.1课,因为他们的部分相同

wl - What lesson from math
lessons - first table
ls - second table
lid - lesson id from lessons table
Just to get non seen lessons.

"SELECT * FROM lessons 
WHERE wl='$math' 
AND id IN(SELECT lid FROM ls WHERE fid='$user' AND seen='0') 
GROUP BY part LIMIT 2";

2 个答案:

答案 0 :(得分:0)

由于这只是为了查找记录,因此可能需要获取每个部分的ID列表,您可以使用GROUP_CONCAT

SELECT part, GROUP_CONCAT(id) as ids
FROM lessons 
WHERE wl='$math' 
AND id IN(SELECT lid FROM ls WHERE fid='$user' AND seen='0') 
GROUP BY part
HAVING COUNT(*) > 1;

如果您希望每个部分和ID更加困难。这些问题通常通过分析函数解决,但MySQL尚未提供它们。这使得有必要两次写入部分查询。

这是如何为用户提供看不见的课程:

SELECT *
FROM lessons 
WHERE wl='$math' 
AND id IN(SELECT lid FROM ls WHERE fid='$user' AND seen='0');

这就是你如何得到在结果中不止一次出现的部分:

SELECT part 
FROM lessons 
WHERE wl='$math' 
AND id IN(SELECT lid FROM ls WHERE fid='$user' AND seen='0') 
GROUP BY part
HAVING COUNT(*) > 1;

两者相结合:

SELECT *
FROM lessons 
WHERE wl='$math' 
AND id IN(SELECT lid FROM ls WHERE fid='$user' AND seen='0')
AND part IN
(
  SELECT part 
  FROM lessons 
  WHERE wl='$math' 
  AND id IN(SELECT lid FROM ls WHERE fid='$user' AND seen='0') 
  GROUP BY part
  HAVING COUNT(*) > 1
);

答案 1 :(得分:0)

对于您的情况“我需要2个因为它们只能有2个相同” - 请使用以下查询:

SELECT 
    id, part
FROM 
    lessons 
WHERE 
    id REGEXP
    (SELECT 
        group_concat(id separator '|')
    FROM 
        lessons 
    WHERE 
        wl='$math' 
        AND id IN (SELECT lid FROM ls WHERE fid='$user' AND seen='0') 
    GROUP BY part
    HAVING count(part) = 2)