MySQL根据IF / CASE语句选择某些行

时间:2012-11-03 01:52:40

标签: mysql select if-statement case multiple-tables

以下是我正在寻找的事情

SELECT id, status, Gid, Uid, note FROM notes LIMIT 10

但状态ID可能不同,它需要类似于以下内容

SELECT a.id, a.status, a.Gid, a.Uid, a.note
FROM notes as a
WHERE
  IF(a.status < 2, DONT SELECT),
  IF(a.status == 2, 
    (SELECT approved FROM friends WHERE Uid = a.Uid AND Fid = ".$_SESSION['Uid'].") 
      IF(approved = 1, SELECT ROW, else DONT)
  )
  IF(a.status == 3, SELECT)
  IF(a.status == 4,
     (SELECT Gid FROM friends WHERE Uid = a.Uid AND Fid = ".$_SESSION['Uid'].")
     IF(Gid == a.Gid, SELECT ROW, else DONT)
ORDER BY id DESC
LIMIT 10

我查了CASE命令,但不知道如何使用它,但是我可以看到它是这样做的方式,但是啊..我不知道该怎么做。 以上是我正在尝试做的一个例子,a.Uid可以是不同的ID,所以当状态== 2或4时,我们需要查看查看用户是批准的朋友还是groupId(Gid) )

任何修复此查询的帮助都会非常感激。如果需要,我可以稍微更改一下注释表,因为它尚未生产,但不鼓励。我愿意接受建议

提前致谢!

1 个答案:

答案 0 :(得分:1)

我认为这会做你想做的事情:

select a.id, a.status, a.Gid, A.Uid, a.note
FROM notes a
LEFT JOIN friends f ON f.Uid = a.Uid AND f.Fid = $_SESSION[Uid]
WHERE (a.status = 2 AND f.approved = 1)
OR a.status = 3
OR (a.status = 4 AND f.Gid = a.Gid)
ORDER BY a.id DESC
LIMIT 10