每个条件只获取一行

时间:2016-08-05 18:29:20

标签: php mysql

我有一张桌子

+-------+-------+--------+
    id  |  myid | userid
+-------+-------+--------+
    1   |  123  |  321
    2   |  321  |  123
    3   |  123  |  444
    4   |  444  |  123
    5   |  123  |  555
+-------+-------+--------+

现在我想获取所有myid='123'

的行

但是当你看到我到处都有,我想获取所有限制为1的行 所以最后我得到了

ids=[1,3,5]

我用它来获取所有行:

SELECT * FROM table 
WHERE (myid='123' AND userid!='123') 
OR (userid='123' AND myid!='123') 
ORDER BY id DESC

但这会获取所有ID 我可以这样说吗?

(
(myid='123' AND userid!='123') 
OR 
(userid='123' AND myid!='123') 
LIMIT 1
)

4 个答案:

答案 0 :(得分:1)

有什么问题
SELECT * 
FROM Table
WHERE (myid = '123' and userid <> '123') OR (myid <> '123' and userid = '123')
ORDER BY id DESC
LIMIT 1

答案 1 :(得分:1)

这可行:

SELECT
    tbl1.id as id,
    t2.my_id as my_id,
    t2.userid as userid
FROM
    (SELECT
        max(t1.id) as id,
    FROM
        table t1
    WHERE
        t1.my_id = 123 or
        t1.userid = 123
    GROUP BY
        if(t1.my_id=123, t1.my_id, t1.userid),
        if(t1.my_id=123, t1.userid, t1.my_id)) tbl1
LEFT OUTER JOIN
    table t2 on t2.id = tbl1.id

这应该会让你ids=[2,4,5]

答案 2 :(得分:0)

也许您需要mysql的group_contact功能

select group_concat(id SEPARATOR ',') from table where myid = '123'
union
select group_concat(id SEPARATOR ',') from table where userid = '123';

这只返回2行

答案 3 :(得分:0)

您可以像这样规范化myid和userid列

select  *,
            case 
                when myid < userid then myid 
                else userid 
            end as u1,
            case 
             when myid > userid then myid 
                else userid
            end as u2
from t

给予

+------+------+--------+------+------+
| id   | myid | userid | u1   | u2   |
+------+------+--------+------+------+
|    1 |  123 |    321 |  123 |  321 |
|    2 |  321 |    123 |  123 |  321 |
|    3 |  123 |    444 |  123 |  444 |
|    4 |  444 |    123 |  123 |  444 |
|    5 |  123 |    555 |  123 |  555 |
+------+------+--------+------+------+

然后计算出像这样的最大ID

select max(id) from
(
select  *,
            case 
                when myid < userid then myid 
                else userid 
            end as u1,
            case 
             when myid > userid then myid 
                else userid
            end as u2
from t
) s
group   by u1,u2

给这个

+---------+
| max(id) |
+---------+
|       2 |
|       4 |
|       5 |
+---------+

然后像这样加入

select   t.*
from        t
where  id in
(
select max(id) from
(
select  *,
            case 
                when myid < userid then myid 
                else userid 
            end as u1,
            case 
             when myid > userid then myid 
                else userid
            end as u2
from t
) s
group by u1,u2
) 

给这个

+------+------+--------+
| id   | myid | userid |
+------+------+--------+
|    2 |  321 |    123 |
|    4 |  444 |    123 |
|    5 |  123 |    555 |
+------+------+--------+

无需硬编码!如果您更喜欢第一次谈话,请将最大值更改为最小值。