我在我的网站上使用旧的MySql版本和php版本4的Oscommeerce。
我的表结构:
| orders_status_history_id | orders_id | orders_status_id |
| 1 | 22 | 3 |
| 2 | 23 | 2 |
| 3 | 24 | 5 |
| 4 | 75 | 5 |
| 5 | 25 | 5 |
| 6 | 30 | 1 |
| 7 | 26 | 2 |
| 8 | 75 | 54 |
| 10 | 22 | 5 |
| 15 | 48 | 6 |
| 16 | 52 | 8 |
| 17 | 32 | 9 |
| 18 | 75 | 54 |
| 19 | 24 | 5 |
| 22 | 20 | 8 |
| 23 | 75 | 54 |
| .. | .. | .. |
| .. | .. | .. |
我的表总共超过2000000行。
orders_status_history_id
列为auto increment
。
所以我的问题是:
我如何获得orders_id
orders_status_id
有两次54 id
的位置?
对于examaple:
如果orders_id
75 orders_status_id
= 54,那么它应该显示orders_id
75,如果没有,则跳过它。
所以我希望输出如此:
| orders_status_id | orders_id |
| 54 | 75 |
我厌倦了以下方式:
$sql = "SELECT
orders_status_history_id, orders_id, orders_status_id
FROM
orders_status_history
Where
(orders_status_history_id > ".$dal." AND orders_status_history_id < ".$al.")
AND
orders_id IN(
Select Distinct
orders_id
From
orders_status_history
Where
(orders_status_history_id > ".$dal." AND orders_status_history_id < ".$al.")
HAVING
count(orders_status_id=54)>2
)";
没用?
SELECT
orders_status_history_id, orders_id, orders_status_id
FROM
orders_status_history
WHERE
(orders_status_history_id > 0 AND orders_status_history_id < 500)
AND
orders_id IN (
Select
orders_id
FROM
orders_status_history
WHERE
(orders_status_history_id > 0 AND orders_status_history_id < 1000)
AND
count(orders_status_id=54) >2
)
我找不到查询来获取所需的结果。
我究竟做错了什么?
提前致谢。
答案 0 :(得分:1)
我会使用group by
和having
:
select orders_id
from orders_status_history
where orders_status_id = 54
group by orders_id
having count(*) >= 2;
如果您确实需要完整的详细信息,请使用join
或in
:
select osh.*
from orders_status_history osh join
(select orders_id
from orders_status_history
where orders_status_id = 54
group by orders_id
having count(*) >= 2
) o
on osh.orders_id = o.orders_id;
答案 1 :(得分:1)
试试这个:
SELECT orders_status_history_id, orders_id, orders_status_id
FROM orders_status_history
WHERE (orders_status_history_id > 0 AND orders_status_history_id < 500) and orders_id IN (
SELECT orders_id
FROM orders_status_history
GROUP BY orders_id
HAVING COUNT(orders_status_history_id) > 1
)
答案 2 :(得分:1)
喜欢这个吗?
SELECT orders_id, orders_status_id
FROM test
AS r
WHERE (
SELECT count(*) FROM test
WHERE orders_id=r.orders_id AND orders_status_id=r.orders_status_id
)>=2
GROUP BY orders_status_id
希望有效。