I have a table with many lines. I need select several (no more than three) lines with certain values and one more. Moreover, need ORDER BY id DESC
and required line position before other. Example:
id | name | group
-----------------
1 | One | null
2 | Two | null
3 | Three| 2
4 | Four | 3
5 | Five | 1
6 | Six | 2
I need lines with group
== 2 (no more than three) and line with id
== 2. Result:
id | name | group
-----------------
2 | Two | null
3 | Three| 2
6 | Six | 2
Line with id
== 2 must be selected, other lines - no more than three. If I use WHERE id = 2 OR group = 2 LIMIT 4
than if exist more than 4 lines with group
== 2, then required line with id
== 2 not selected.
How solve the problem in one SQL-request?
答案 0 :(得分:1)
您可以尝试使用UNION
。另请注意,group
是MySQL的保留字。
SELECT aa.*
FROM (
SELECT id, firstname, lastname
FROM user
WHERE id IN (1, 2, 3, 4)
LIMIT 2
UNION ALL
SELECT id, firstname, lastname
FROM user
WHERE id = 5
) AS aa
答案 1 :(得分:0)
select * from table_name where id=2
union all
select * from table_name where group=2