I want to get all rows with same part value, like
1. lesson 1 part=1
2. lesson 1.1 part=1
3. lesson 2 part=2
I want to get lesson 1 and 1.1 because their part is equal
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";
As this is just for you to look up the records, it probably suffices to get a list of IDs for each part, for which you can use 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;
If you wanted a row per part and ID that would be more difficult. Such problems are usually solved with analytic functions, but MySQL doesn't feature them yet. This makes it necessary to write part of the query twice.
This is how to get the unseen lessons for the user:
SELECT *
FROM lessons
WHERE wl='$math'
AND id IN(SELECT lid FROM ls WHERE fid='$user' AND seen='0');
And this is how you get the parts that appear more than once in the results:
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;
The two combined:
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
);
For your condition "I need 2 same because they can have only 2 same" - use the following query:
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.